출처 http://c-faq.com

Q: Does *p++ increment p, or what it points to?

   

A: The postfix ++ and -- operators essentially have higher precedence than the prefix unary operators. Therefore, *p++ is equivalent to *(p++); it increments p, and returns the value which p pointed to before p was incremented. To increment the value pointed to by p, use (*p)++ (or perhaps ++*p, if the evaluation order of the side effect doesn't matter).

References: K&R1 Sec. 5.1 p. 91

K&R2 Sec. 5.1 p. 95

ISO Sec. 6.3.2, Sec. 6.3.3

H&S Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp. 199-200

반응형

'Language > C' 카테고리의 다른 글

msgsnd/ msgrcv 함수 예제  (167) 2012.07.12
C FAQ (포인터 증가 2)  (7) 2012.07.12
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가?  (7) 2012.07.12
C FAQ (malloc 오류)  (7) 2012.07.12
C FAQ (포인터 선언 에러)  (7) 2012.07.12

 출처 http://c-faq.com

Q: What are pointers really good for, anyway?

   

A: They're good for lots of things, such as:

  • dynamically-allocated arrays (see questions 6.14 and 6.16)
  • generic access to several similar variables
  • (simulated) by-reference function parameters (see question 4.8 and 20.1)
  • malloc'ed data structures of all kinds, especially trees and linked lists
  • walking over arrays (for example, while parsing strings)
  • efficient, by-reference ``copies'' of arrays and structures, especially as function parameters

(Note that this is hardly a comprehensive list!)

See also question 6.8.

   

    

반응형

'Language > C' 카테고리의 다른 글

C FAQ (포인터 증가 2)  (7) 2012.07.12
C FAQ (포인터 증가에 대해서)  (7) 2012.07.12
C FAQ (malloc 오류)  (7) 2012.07.12
C FAQ (포인터 선언 에러)  (7) 2012.07.12
mkfifo 함수 예제  (471) 2012.07.06

출처 http://c-faq.com

Q: I'm trying to declare a pointer and allocate some space for it, but it's not working. What's wrong with this code?

char *p;
*p = malloc(10);

 => 언뜻 보기에는 될것 같이 생겼다..

A: The pointer you declared is p, not *p. When you're manipulating the pointer itself (for example when you're setting it to make it point somewhere), you just use the name of the pointer:

        p = malloc(10);

It's when you're manipulating the pointed-to memory that you use * as an indirection operator:

        *p = 'H';

(It's easy to make the mistake shown in the question, though, because if you had used the malloc call as an initializer in the declaration of a local variable, it would have looked like this:

        char *p = malloc(10);

When you break an initialized pointer declaration up into a declaration and a later assignment, you have to remember to remove the *.)

In summary, in an expression, p is the pointer and *p is what it points to (a char, in this example).

See also questions 1.21, 7.1, 7.3c, and 8.3.

References: CT&P Sec. 3.1 p. 28

반응형

'Language > C' 카테고리의 다른 글

C FAQ (포인터 증가에 대해서)  (7) 2012.07.12
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가?  (7) 2012.07.12
C FAQ (포인터 선언 에러)  (7) 2012.07.12
mkfifo 함수 예제  (471) 2012.07.06
popen 함수 pclose 함수 예제  (175) 2012.07.06

출처 : http://c-faq.com/

Q: What's wrong with this declaration?

char* p1, p2;

I get errors when I try to use p2.

   

A: Nothing is wrong with the declaration--except that it doesn't do what you probably want. The * in a pointer declaration is not part of the base type; it is part of the declarator containing the name being declared (see question 1.21). That is, in C, the syntax and interpretation of a declaration is not really

        type identifier ;

but rather

        base_type thing_that_gives_base_type ;

where ``thing_that_gives_base_type''--the declarator--is either a simple identifier, or a notation like *p or a[10] or f() indicating that the variable being declared is a pointer to, array of, or function returning that base_type. (Of course, more complicated declarators are possible as well.)

In the declaration as written in the question, no matter what the whitespace suggests, the base type is char and the first declarator is ``* p1'', and since the declarator contains a *, it declares p1 as a pointer-to-char. The declarator for p2, however, contains nothing but p2, so p2 is declared as a plain char, probably not what was intended. To declare two pointers within the same declaration, use

        char *p1, *p2;

Since the * is part of the declarator, it's best to use whitespace as shown; writing char* invites mistakes and confusion.

See also question 1.13.

Additional links: Bjarne Stroustrup's opinion

반응형

'Language > C' 카테고리의 다른 글

C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가?  (7) 2012.07.12
C FAQ (malloc 오류)  (7) 2012.07.12
mkfifo 함수 예제  (471) 2012.07.06
popen 함수 pclose 함수 예제  (175) 2012.07.06
pipe 함수 예제  (451) 2012.07.06

mkfifo(const char *pathname, mode_t mode)

- 2개의 매개 변수가 필요하네.

- mkfifo(파이프사용할 파일명, 모드)

- 이걸로 FIFO 파일을 생성하면 이후로는 이파일을 가지고 파이프로 이동할 수 있다.

- 동일한 fd를 이용한다면 다른 프로세스에서도 메시지를 받을 수 있다.

- 주고 받는 양방향 불가.

 

수신하는 곳

#include 
#include 
#include 
#include 
#include 

#define  FIFO_FILE   "/tmp/fifo"
#define  BUFF_SIZE   1024

int main( void)
{
    int   counter = 0;
    int   fd;
    char  buff[BUFF_SIZE];

    if(mkfifo(FIFO_FILE, 0666) == -1)
    {
        perror( "mkfifo() failed\n");
        return -1;
    }

    if (( fd = open( FIFO_FILE, O_RDWR)) == -1)
    {
        perror( "open() failed\n");
        return -2;
    }
    printf("FD=%d\n", fd);

    while( 1 )
    {
        memset( buff, 0x00, BUFF_SIZE);
        read( fd, buff, BUFF_SIZE);
        printf( "%d: %s\n", counter++, buff);
    }
    close(fd);
    return 0;
}
/* The end of function */
송신하는 곳

#include 
#include 
#include 
#include 
#include 

#define  FIFO_FILE   "/tmp/fifo"

int main( void)
{
    int   fd;
    char *str   = "TEST FIFO IPC";

    if ( -1 == ( fd = open( FIFO_FILE, O_WRONLY)))
    {
        perror( "open() failed\n");
        return -1;
    }
    printf("FD=%d\n", fd);

    write(fd, str, strlen(str));
    close(fd);
    return 0;
}
/* The end of function */

수신쪽 결과 
$ ./recv 
FD=3
0: TEST FIFO IPC
1: TEST FIFO IPC
2: TEST FIFO IPC

송신쪽 결과
$ ./send 
FD=3
$ ./send 
FD=3
$ ./send 
FD=3

 

=============================================

open함수는 파일 열고 fd를 반환한다.

write함수는 바로 그 fd에다가 쓴다.

같은 시스템에서 같은 파일을 열면

동일한 fd를 가지게 되므로 위와 같이 쓸 수 있다.

=============================================

출처 http://forum.falinux.com/zbxe/?document_srl=420145

반응형

'Language > C' 카테고리의 다른 글

C FAQ (malloc 오류)  (7) 2012.07.12
C FAQ (포인터 선언 에러)  (7) 2012.07.12
popen 함수 pclose 함수 예제  (175) 2012.07.06
pipe 함수 예제  (451) 2012.07.06
다차원 배열을 1차원 배열로 변경하고자 할 때  (161) 2011.08.11

popen()

- 명령어를 shell을 기동 시켜서 열고 pipe로 연결한다.

- 이를 위해서 내부적으로 fork(), pipe()를 사용한다.

- 실행 쉘인 /bin/sh에 -c 옵션을 사용하여 전달

 

pclose()

- popen으로 열린 파이프 핸들 사용을 종료한다.

 

 

 

#include 
#include 
#include 
#include 

int main()
{
    FILE *fp = NULL;
    char cmd[1024] = {0,};
    char buffer[1024];
    pid_t   ppid;
    pid_t   *pid;

    snprintf(cmd, sizeof(cmd), "pidof -x /usr/sbin/sshd");

    fp = popen(cmd, "r");
    if( fp==NULL) {
        return -1;
    }

    fgets(buffer, sizeof(buffer), fp) ;
    printf("%s\n", buffer);
    pclose(fp);
    return 0;
}
실행결과 화면
$ ./a.out 
5967

 

 

 

 

 

 

 

 

 

=============================================

 

그냥 pidof 명령을 실행해준다. 내부의 ssh데몬의 pid를 가져다가

뿌려주는 역할을 한다.

반응형

'Language > C' 카테고리의 다른 글

C FAQ (포인터 선언 에러)  (7) 2012.07.12
mkfifo 함수 예제  (471) 2012.07.06
pipe 함수 예제  (451) 2012.07.06
다차원 배열을 1차원 배열로 변경하고자 할 때  (161) 2011.08.11
C언어 - 스트림(Stream)이란?  (154) 2011.08.11

pipe()

- 하나의 파이프 및 파이프에 대한 두 개의 파일 디스크립터가 생성

- 하나의 파이프를 프로세스들이 공유

#include "sys/types.h"
#include 
#include 
#include 
#include 

#define MAXLINE 4096 /* max line length */ 

/* err_sys("") --> return(1) */

int main(void)
{
    int n, fd[2];
    pid_t pid;
    char line[MAXLINE];

    if (pipe(fd) < 0) {
        printf("pipe error \n");
        return(-1);
        /* err_sys("pipe error"); */
    }

    if ( (pid = fork()) < 0) {
        printf("fork error \n");
        return(-2);
        /* err_sys("fork error"); */

    } else if (pid > 0) { /* parent */

        close(fd[0]);
        write(fd[1], "Hello world\n", 12);

    } else { /* child */
        close(fd[1]);
        n = read(fd[0], line, MAXLINE);
        write(STDOUT_FILENO, line, n);
    }

    return(0);
}
/* The end of function */

=============================================================

파이브열고

포크로 자식 프로세스 만들어다가

read시키는데

이떄, 부모프로세스는 write으로 파이프의 내용을 읽어온다.

결국 위의 코드의 결과는

printf("%s\n", "Hello world");

와 동일하게 나옴. write함수에서 fd들어갈곳에 STDOUT_FILENO플래그를

넣었으니깐.

=============================================================

pipe() 함수는 파일 디스크립터 쌍을 생성하네, 2개 생성하는데.

filedes[2] => filedes[0] Read, filedes[1] Write. 용도로 만든다.

사용법
#include <unistd.h>

int pipe(int filedes[2]);

=============================================================

fork()함수는 Child process 생성하는 기본적인 멀티 프로세싱 함수

사용법
#include <unistd.h>

pid_t fork(void);

=============================================================

close()함수는 pipe로 열린 descriptor 닫아버리는 함수

SYNOPSIS
#include <unistd.h>

int close(int fd);

=============================================================


출처

1. advanced programming in the unix environment

 2. http://gatolu.tistory.com/entry/%ED%8C%8C%EC%9D%B4%ED%94%84-%ED%95%A8%EC%88%98 

반응형

'Language > C' 카테고리의 다른 글

mkfifo 함수 예제  (471) 2012.07.06
popen 함수 pclose 함수 예제  (175) 2012.07.06
다차원 배열을 1차원 배열로 변경하고자 할 때  (161) 2011.08.11
C언어 - 스트림(Stream)이란?  (154) 2011.08.11
리눅스 시스템 프로그래밍 8장 IPC  (148) 2011.08.11

다차원 배열을 1차원 배열로 변경하고자 할 때

Programming/C / 2009/08/31 15:53

1. 2차원 배열

a[IMAX][JMAX]

b[IMAX*JMAX]

b[i*JMAX+j] = a[i][j]

   

2. 3차원 배열

a[IMAX][JMAX][KMAX]

b[IMAX*JMAX*KMAX]

b[i*JMAX*KMAX+j*KMAX+k]=a[i][j][k]

   

<http://revoman.nudecode.org/entry/다차원-배열을-1차원-배열로-변경하고자-->에서 삽입

반응형

'Language > C' 카테고리의 다른 글

popen 함수 pclose 함수 예제  (175) 2012.07.06
pipe 함수 예제  (451) 2012.07.06
C언어 - 스트림(Stream)이란?  (154) 2011.08.11
리눅스 시스템 프로그래밍 8장 IPC  (148) 2011.08.11
call by value와 call by reference | KLDP  (155) 2011.08.11

+ Recent posts