Print string array elements in c

I created a function that takes a pointer to the first element in a C-String array. This is an array and how I did it:

char element1[60] = "ubunz"; char element2[60] = "uasdasffdnz"; char* array[10] = {element1,element2}; 

Then I created a pointer to the first element in the array:

 char *pointertoarray = &array[0]; 

Then I passed a pointer to a function that I did:

 void printoutarray(char *pointertoarray){ int i = 0; while (i < 2){ printf("\n Element is: %s \n", *pointertoarray); pointertoarray = pointertoarray + 1; i = i+1; } } 

When I run the program, the array is never printed.

I did this program before in C ++, but I used the string type STL and made a pointer to an array of strings. I think my problem is how I'm going to make an array of strings in C and make a pointer to it.

+4
source share
3 answers

When printf () is called with% s, it will more or less do the following

 for(i = 0; pointer[i] != '\0'; i++) { printf("%c", pointer[i]); } 

What you do is something like

 for(i = 0; pointer[i] != '\0'; i++) { printf("\n Element is %c", pointer[i]); } 

When you reference certain elements in an array, you must use the AND index ie pointer [0], in which case 0 is an index, and the pointer is a pointer. The above for loops will move the entire array one index at a time, because ā€œiā€ is the index, and ā€œiā€ increases at the end of each turn of the loop, and the loop will continue to spin until it reaches the final NULL character in the array.

So, you can try something about this.

 void printoutarray(char *pointertoarray) { for(i = 0; i <= 2; i++) { printf("\n Element is: %s \n", pointertoarray[i]); } } 
+6
source

It:

 char *pointertoarray = &array[0]; 

compile without warning on your compiler? If so, your compiler is broken. Read the errors and warnings that it prints.

&array[0] is char** , not a char*

+5
source

Remove asterisk

 printf("\n Element is: %s \n", pointertoarray); 
+1
source

All Articles