Loop rows without loop or counter in C

My goal is to scroll through a predefined set of lines when printing each of them on a separate line without using a counter variable. The lines I commented on are working code, but a counter is required. The four lines beneath it surpassed me.

int main(int argc,char* argv[]){ char *astring[500]; astring[0]=(char*)"ABC"; astring[1]=(char*)"DEF"; astring[2]=(char*)"GHI"; astring[3]=(char*)NULL; //long count; //for (count=0;count<4;count++){ //printf("%s\n",astring[count]); //} char *p=*astring; while (*p++){ printf("%s\n",*p); } return 0; } 

I tried the following options without success.

This code:

  char *p=*astring; while (*p++){ printf("%s\n",*p); } 

It compiles normally, but after execution, a segmentation error occurs, and the program immediately exits from it.

I tried:

  while (**p++){ printf("%s\n",*p); } 

and the program will not compile due to invalid type argument of 'unary *' .

Then I changed char *p=*astring; on char *p=astring; and got a warning initialization from incompatible pointer type

Then I also tried char *p=**astring; and received this warning for the compiler: initialization makes pointer from integer without a cast

Should I be confused with the stars or is this what I'm trying to make impossible? Anyone have a solution?

+4
source share
3 answers

You can just write

 for ( char **p = astring; *p; ++p ) puts( *p ); 

Or, if your compiler does not support C99, place the pointer declaration after the array declaration

 char *astring[500]; char **p; //... for ( p = astring; *p; ++p ) puts( *p ); 

If you have an array with elements of type T , then the array used in the expressions is converted to a pointer to its first element. So, if there is an announcement

 T array[N]; 

then you can write

 T *p = array; 

In your program, you have an array of char * elements. So T corresponds to char * . And you can write

 typedef char * T; T astring[500]; T *p = astring; 

i.e. p will be of type char **

Please note that casting is not necessary.

 astring[0]=(char*)"ABC"; astring[1]=(char*)"DEF"; astring[2]=(char*)"GHI"; astring[3]=(char*)NULL; 

You can write

 char *astring[500] = { "ABC", "DEF", "GHI"/*, NULL */ }; 
+2
source
 char** p = astring; while (*p != NULL){ printf("%s\n", *p); p++; } 
+2
source

I figured out one way to do this:

 int main(int argc,char* argv[]){ char *astring[500]={"ABC","DEF","GHI","JKL",NULL}; char **p=astring; while (*p != NULL){ printf("%s\n",*p); *p++; } return 0; } 
0
source

All Articles