How to increase the ptr to the first element of an array of strings

Viewed 48

I have initialized an array of strings. I want to output the individual strings via a while loop. I pass a function the pointer to the array of strings. In my current version I only position on the individual chars, I cant get it..

    char * Menuepunkte[] = 
{
    "Exit", 
    "Start-Quiz", 
    "Random-Questions", 
    "Load-Questions", 
    "Generator"
};


int MENUE (char * Unterpunkte)
{

  while (Unterpunkte != NULL)
  {
    printf("In: %s len: %i \n", Unterpunkte, strlen(Unterpunkte));
    ++Unterpunkte;
    while(getchar()!='\n');
  }
  ..
2 Answers

You forget to NULL terminate the array, try:

#include <stdio.h>

static void func(char *ptr[])
{
    while (*ptr)
    {
        puts(*ptr);
        ptr++;
    }
}

int main(void)
{
    char *arr[] = 
    {
        "Exit", 
        "Start-Quiz", 
        "Random-Questions", 
        "Load-Questions", 
        "Generator",
        NULL
    };

    func(arr);
    return 0;
}

Output:

Exit
Start-Quiz
Random-Questions
Load-Questions
Generator

So your function should look like:

int MENUE (char *Unterpunkte[]) // or `char **Unterpunkte` (a pointer to pointer)
{

  while (*Unterpunkte != NULL)
  {
    printf("In: %s len: %i \n", *Unterpunkte, strlen(*Unterpunkte));
    ++Unterpunkte;
    ...
  }
/* count is the number of strings you have */
void MENUE(char** Unterpunkte, int count) {
    while (count--) {
        printf("In: %s, len: %i\n", *Unterpunkte, strlen(*Unterpunkte));
        ++Unterpunkte;
    }
}
Related