0
#include<stdio.h>
int main(){

char*s[]={"we will teach you how to","Move a mountain","Level a building","Erase the past","Make a million"};

   printf("%u",sizeof(s));

return 0; }

Running this will output 20. Shouldn't the size be = no.of elements in each array x no of arrays x sizeof(char)? Also sizeof(s+1) prints 4 bytes. Furthermore, how can I obtain the number of pointer arrays and no. of elements in each pointer array from the above mentioned code without hard coding?

1 Answers1

1

There are 5 entries in your array s. Each entry is a char *. Hence sizeof(s) is 5*sizeof(char *). It appears you are running on a 32 bit system so pointers are 4 bytes in size. Hence the total size is 20 bytes.

how can I obtain the number of pointer arrays and no. of elements in each pointer array

That part of the question is a bit unclear. There is only one "pointer array" which is s. To get the number of elements in the array you can do:

sizeof(s) / sizeof(*s)

To get the length of the string at array index i you can do:

strlen(s[i])
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • The reason I asked is so that I can use it in a for loop to count the number of occurences of the letter 'e'. So i was unclear as to how to get the number of elements. Is it okay to use the condition s[i]!='\0' ? – Vinod Antony Feb 29 '20 at 06:31
  • No it's not ok. It's a type error. `s[i]` is of type `char *`. `'\0'` is of type `char`. You cannot compare these two types to each other. – kaylum Feb 29 '20 at 06:34
  • @VinodAntony the only way a check like `s[i] != NULL` works is if you set a *sentinel* `NULL` as the next pointer after the last valid pointer in your array. (the same way `char *argv[]` does, or that `execv`, `execvp`, and `execve` require) – David C. Rankin Feb 29 '20 at 09:07