출처 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)  (6) 2012.07.12
C FAQ (포인터 증가에 대해서)  (6) 2012.07.12
C FAQ (malloc 오류)  (6) 2012.07.12
C FAQ (포인터 선언 에러)  (6) 2012.07.12
mkfifo 함수 예제  (10) 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 (포인터 증가에 대해서)  (6) 2012.07.12
C-FAQ 어찌되었건 pointer 쓰면 정말 좋은가?  (6) 2012.07.12
C FAQ (포인터 선언 에러)  (6) 2012.07.12
mkfifo 함수 예제  (10) 2012.07.06
popen 함수 pclose 함수 예제  (6) 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 쓰면 정말 좋은가?  (6) 2012.07.12
C FAQ (malloc 오류)  (6) 2012.07.12
mkfifo 함수 예제  (10) 2012.07.06
popen 함수 pclose 함수 예제  (6) 2012.07.06
pipe 함수 예제  (14) 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 오류)  (6) 2012.07.12
C FAQ (포인터 선언 에러)  (6) 2012.07.12
popen 함수 pclose 함수 예제  (6) 2012.07.06
pipe 함수 예제  (14) 2012.07.06
다차원 배열을 1차원 배열로 변경하고자 할 때  (6) 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 (포인터 선언 에러)  (6) 2012.07.12
mkfifo 함수 예제  (10) 2012.07.06
pipe 함수 예제  (14) 2012.07.06
다차원 배열을 1차원 배열로 변경하고자 할 때  (6) 2011.08.11
C언어 - 스트림(Stream)이란?  (6) 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 

반응형

다차원 배열을 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 함수 예제  (6) 2012.07.06
pipe 함수 예제  (14) 2012.07.06
C언어 - 스트림(Stream)이란?  (6) 2011.08.11
리눅스 시스템 프로그래밍 8장 IPC  (6) 2011.08.11
call by value와 call by reference | KLDP  (6) 2011.08.11

(카아알) Karl's the story of a proper life.

C언어 - 스트림(Stream)이란?

2009/04/21 11:02 in I'm Developer.

스트림이란 일련의 문자열이며, C언어에서 자료를 입출력하기 위하여 사용하는 것으로

프로그램과 입출력 장치 사이에서 입출력 자료들을 중계하는 역할을 담당합니다.

   

스트림(Stream)이란 글자 그대로 해석하자면 '흐름', '흐르다'라는 뜻으로,

데이터를 입력 받거나 출력하려면 먼저 스트림에 일련의 바이트 문자들을 기록한 다음

스트림으로부터 데이터를 읽거나 특정 장치에 데이터를 출력하는 것입니다.

스트림의 장점

  

프로그램의 입출력 동작이 입출력 장치와는 독립적이기 때문에, 스트림이 어디로 가는지

어디에서 오는지에 대해 신경 쓸 필요가 없습니다.

  

즉, 프로그램 작성시 입출력 장치의 종류에 따라 다르게 프로그램을 작성할 필요없이

스트림을 통하여 입출력 하도록 프로그램을 작성하면, C라이브러리 함수와 운영체제에 의하여

자동으로 원하는 장치에 입출력 됩니다.

     

   

   

표준 스트림

  

C언어가 제공하고 있는 표준 입출력 스트림은 다음과 같습니다.

스트림

설명

장치

stdin

표준 입력

키보드

stdout

표준 출력

화면

stderr

표준 에러

화면

stdprn

표준 프린터

프린터

stdaux

표준 보조

직렬포트

 

  

스트림은 C프로그램이 실행될 때 자동으로 열리고 프로그램 종료될 때 자동으로

닫히기 때문에 프로그램을 위한 특별한 조치가 필요 없습니다.

스트림의 종류

  

스트림의 종류에는 텍스트 스트림과 바이너리 스트림이 있습니다.

  

텍스트 스트림

바이너리 스트림

텍스트 문자만을 처리

   

(예) 표준 입출력 스트림

자료를 바이트 단위로 처리하기

때문에 텍스트 문자뿐만 아니라

모든 종류의 데이터를 처리

(예) 파일을 사용한 입출력

 

반응형

+ Recent posts