Monday, August 07, 2006

Array and pointer

char a[] = "Hello, world!";
that's an initialization. You are allowed to initialize arrays when you define them.
char a[];
a = "help";

you cannot assign to them. When you need to copy the contents of one array to another, you must do so explicitly(strcpy);
void f(char str[])
str = "help";

str is a pointer (of type char *), and it is legal to assign to it. same as void(char *str)
char str[10];
printf("%d\n", sizeof(str)); // 10
f(char a[10])
int i = sizeof(a);
printf("%d\n", i); // 4

Sizeof reports the size of the pointer.
Get the number of the elements, simply divide the size of the entire array by the size of one element:
int array[] = {1, 2, 3};
int narray = sizeof(array) / sizeof(array[0]);

No comments:

Post a Comment