Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out elements of an array of strings in c

Tags:

arrays

c

cstring

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.

like image 358
turnt Avatar asked Jan 13 '13 18:01

turnt


People also ask

How do I print the string elements of an array?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

What is array of strings in C?

The string is a collection of characters, an array of a string is an array of arrays of characters. Each string is terminated with a null character. An array of a string is one of the most common applications of two-dimensional arrays. All in One Software Development Bundle (600+ Courses, 50+ projects)


1 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 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]);
  }
}
like image 98
John Vulconshinz Avatar answered Sep 18 '22 01:09

John Vulconshinz