简体   繁体   中英

Why does For-Loop terminate all the codes after itself?

After the for-loop finishes printing myArray, it simply doesn't let any further code to progress anymore and returns the value -1073741819.

int main() {

char *myArray[]={"Carmaker1","Carmaker2","Carmaker3","Carmaker4","Carmaker5","Carmaker6"};

for ( int i = 0 ; myArray[i] != '\0' ; i++ ) {
    
    printf("%s ",*(myArray+i));
}
/*
.
.
.
.Some code here...
.
.
.
*/

The expression

myArray[i] != '\0' 

is equivalent to

myArray[i] != NULL 

But your array does not contain an element with the value NULL.

So either declare the array like

char *myArray[]={"Carmaker1","Carmaker2","Carmaker3","Carmaker4","Carmaker5","Carmaker6", NULL};

(appending an initializer with the value NULL ) and use the loop

for ( int i = 0 ; myArray[i] != NULL ; i++ ) {
    
    printf("%s ",*(myArray+i));
}

Or you can append the array with an empty string like

char *myArray[]={"Carmaker1","Carmaker2","Carmaker3","Carmaker4","Carmaker5","Carmaker6", ""};

and write the loop like

for ( int i = 0 ; myArray[i][0] != '\0' ; i++ ) {
    
    printf("%s ",*(myArray+i));
}

Or using the current declaration of the array change the loop the following way

for ( size_t i = 0 ; i!= sizeof( myArray ) / sizeof( *myArray ) ; i++ ) {
    
    printf("%s ",*(myArray+i));
}

You code has a bug, as suggested in the comments, you can fix your code as shown below,

#include<stdio.h>

int main() {

char *myArray[]=  {"Carmaker1","Carmaker2","Carmaker3","Carmaker4","Carmaker5","Carmaker6", ""};

for ( int i = 0 ; *myArray[i] != '\0' ; i++ ) {printf("%d, %s \n",i, *(myArray+i)); }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM