0

I want to create an array of strings where the user defines the items that are in the array. That is, I will ask for the user to enter the elements of the array (using scanf). I also have a function that prints the elements of that array. So, I want to pass the array of strings to that function.

I have tried researching a lot about this but could not understand anything. I came across a solution where I can pass the array of strings to a function using char ** but the elements can't be defined at run time.

This is the solution I came across.

#include <stdio.h>
#include <stdlib.h>

void print(char **, int size);

int main(){

    char *stringArray[3];

    stringArray[0] = "Word0";
    stringArray[1] = "Word1";
    stringArray[2] = "Word2";

    print(stringArray, 3);

    return 0;
}

void print(char **ptr, int size){
    int i;

    for(i=0; i<size; i++){
        printf("%s\n", ptr[i]);
    }
}

But I want the elements to be entered by the user. Something like this, but this doesn't work. (Why?)

#include <stdio.h>
#include <stdlib.h>

void print(char **, int size);

int main(){

    char *stringArray[3];

    for(int i=0; i<3; i++){
        scanf("%s", stringArray[i]);
    }
    
    print(stringArray, 3);

    return 0;
}

void print(char **ptr, int size){
    int i;

    for(i=0; i<size; i++){
        printf("%s\n", ptr[i]);
    }
}

The concepts of a pointer to a pointer char ** is new to me and I would request you to explain this to me as you would explain this to a complete beginner. Any help regarding this is highly appreciated. Thank you in Advance.

Developer
  • 425
  • 3
  • 15

1 Answers1

1

You must allocate some buffer for strings before using pointers.

int main(){

    char *stringArray[3];

    for(int i=0; i<3; i++){
        stringArray[i] = malloc(1024 * 1024); /* allocate buffer, hoping user input won't be so long */
        if (stringArray[i] == NULL) { /* check if allocation is successful */
            perror("malloc");
            return 1;
        }
        scanf("%s", stringArray[i]);
    }

    print(stringArray, 3);

    for(int i=0; i<3; i++){
        free(stringArray[i]); /* free allocated things */
    }

    return 0;
}

For more information, see c - Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer - Stack Overflow

MikeCAT
  • 73,922
  • 11
  • 45
  • 70