-2

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...
.
.
.
*/
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • In the expression `myArray[i] != '\0'`, why are you comparing a pointer with a character? If you want the poiner array to be zero terminated, you must make it zero terminated yourself, by adding a` NULL` at the end of the array. Then you should compare with `NULL` instead of '\0'. – Andreas Wenzel Oct 12 '20 at 20:18
  • the condition in the loop causes the program to crash. \0 In C is mostly used to indicate the termination of a character string NOT an array. – YosefAhab Oct 12 '20 at 20:21

2 Answers2

2

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));
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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)); }

}
CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • 1
    I believe a `NULL`-terminated array is a better solution than an array terminated by an empty string. This is also how [`argv`](https://en.cppreference.com/w/c/language/main_function) is terminated. However, you are right that this is the closest solution for the code the OP posted. – Andreas Wenzel Oct 12 '20 at 20:29