我正在编写一个 C 程序来理解字符串和指针。除了 char* [] 和 char**[] 的 sizeof 操作之外,一切都有效。
这是我的代码:
int main(){
puts("");
char src[]= "rabbit";
char* src2[] = {"rabbit","dog","monkey"};
char* src3[] = {"fish","horse","dolphin"};
char** src4[] = {src2,src3};
int i,j;
printf("Size of the char array only is %d\n",sizeof(src));
printf("Size of the array of string pointers only is %d\n", sizeof(&src2));
printf("Size of the array of pointers to string pointers only %d\n\n", sizeof(src4));
puts("Single char array is:");
for(i = 0; i<sizeof(src)-1; i++){
printf("%c,",src[i]);
}
puts ("\n");
puts("Array of strings:");
puts(src2[0]);
puts(src2[1]);
puts(src2[2]);
puts("");
puts("Printing the char** [] contents ");
for(i=0; i<2; i++){
for(j=0; j < 3;j++){
puts(src4[i][j]);
}
}
puts("");
return 0;
}
那么如何获取 char* [] 和 char** [] 中的元素数量呢?另外,如果我声明 char*[] src2 = {"rabbit","dog","monkey"}; 仅作为 char*[] m_src。那么我是否必须为添加到此数组中的每个元素分配空间?例如
如果我做了
// Code segment changed for char*[]
char* m_src[];
// could I do this
m_src = malloc(3 * sizeof(char*));
m_src[0] = "rabbit";
m_src[1] = "dog";
m_src[2] = "monkey";
/* Even more is there a way to dynamically add elements to the
array like mallocing space for a single element at a time and tacking it onto the
array char* m_src? */