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.