I am writing a C program to understand strings and pointers. Everything works except the sizeof operation for a char* [] and char**[].
Here is my code:
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;
}
So how do get the number of elements in char* [] and char** [] ? Also on another note if I for example declare char*[] src2 = {"rabbit","dog","monkey"}; as only char*[] m_src. Then do I have to malloc space for each element I add into this array ? for example
If I had instead done
// 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? */