char * foo() {
static char ret[];
return (ret);
}
등의 코드를 검토한 글
char * foo() {
static char ret[];
return (ret);
}
등의 코드를 검토한 글
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int main ()
{
FILE *fp;
char buf[1024];
char *token;
int cnt;
fp = popen("/usr/bin/wc -l abc.txt", "r");
if (fp == NULL)
{
printf("ERROR:popen fail\n");
exit(0);
}
fread(buf, 1, 1024, fp);
pclose(fp);
printf("buf:%s\n", buf);
token = (char *) strtok(buf, " ");
printf("token:%s\n", token);
cnt = atoi(token);
printf("cnt:%d\n", cnt);
}
배열 크기를 가변적으로 하고 싶을 때, 아래처럼 사용하는 경우가 많다. 두 개 이상의
멤버를 갖는 구조체를 선언하고 마지막 멤버의 크기를 1 로 정의하면 마지막 멤버의
개수를 가변적으로 사용할 수 있다.
이 기법은 보통 struct hack 이라고 부른다. 하지만 이 방법은 Ansi C 에 정의되어 있지
않은 것이라고 한다.
struct A {
char aa1[10];
char aa2[20];
}
struct B {
char bb1[10];
char bb2[20];
struct A a_struct[1];
};
struct B *p = malloc(sizeof(struct B) + (sizeof(struct A) * 100));
C 99 에서는 가변 크기 배열을 쓸 수 있다고 한다.
http://stackoverflow.com/questions/3711233/is-the-struct-hack-technically-undefined-behavior
를 참고.
sizeof(((struct person *) 0)->name).
출전: http://kerneltrap.org/node/16153