0

I am just playing around with a simple c code. I want to print all the days string in the days array pointer. However I am running to segmentation fault. The problem lies in the for loop. What am I doing wrong here. Thanks

main(){
  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",\
                        "Thursday", "Friday", "Saturday", "Sunday"};
  int i;

  for(i = 0; i < sizeof(days); ++i)
   printf( "%s\n", days[i]);
}
nalzok
  • 14,965
  • 21
  • 72
  • 139

2 Answers2

2
int main(){
  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",\
                        "Thursday", "Friday", "Saturday", "Sunday"};
  size_t i;
  for(i = 0; i < sizeof days / sizeof days[0]; ++i)
   printf( "%s\n", days[i]);
}

sizeof day yield the size of the whole array, so you have to divide it with the size of one of its elements to get the number of element it contains.

nalzok
  • 14,965
  • 21
  • 72
  • 139
2

change the for statement to

for( i = 0; i < ( sizeof(days)/sizeof(days[0]) ); ++i )

The sizeof expression gives you the number of elements in the array, as opposed to the number of bytes it takes

A classic way to do this is a macro

#define SIZEOF( X ) ( sizeof( X )/sizeof( X[0]) )

and then use SIZEOF instead of sizeof

infixed
  • 1,155
  • 7
  • 15