carrayscstring

Print out elements of an array of strings in c


I've created a function that takes a pointer to the first element in a C-String array. This is the array, and how I went about making 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 the pointer to the function I made:

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 never prints out.

I've done this program before in C++ but I used the STL string type, and made a pointer to an array of strings. I think my problem lies with the way I'm going about making an array of strings in C, and making a pointer to it.


Solution

  • 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 want do is something like

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

    When you are referencing specific elements in an array you must use a pointer AND an index i.e. pointer[0] in this case 0 is the index and 'pointer' is the pointer. The above for loops will move through the entire array one index at a time because 'i' is the index and 'i' increases at the end of every rotation of loop and the loop will continue to rotate until it reaches the terminating NULL character in the array.

    So you might want to try something along the lines of this.

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