Reputation: 105
i have to insert strings in array of string in C. I wrote a function but it didn't work. Can you help me?
When i'm going to print the array, program crashes.
Thanks
int leggi(char **a, int *len) {
int i;
scanf("%d", len);
if(*len <= 0) return 1;
a = (char **) malloc(*len * sizeof(char *));
if(a == NULL) return 1;
for( i = 0; i < *len; i++ )
{
a[i]=(char *)malloc(101*sizeof(char));
scanf("%s", &a[i]);
}
printf("Saved\n");
return 0;
}
int main() {
int i, n;
char **A;
if(leggi(A, &n)) return 1;
printf("%d\n",n);
for( i = 0; i < n; i++ )
{
printf("printf\n");
printf("%s\n", &A[i]);
}
return 0;
}
Upvotes: 0
Views: 105
Reputation: 124
Change scanf("%s", &a[i])
to scanf("%s", a[i])
, a[i] is the pointer to the first character in your string, getting the address of it would just return the address of the pointer, not the actual first char. Another thing to note is that you are not actually modifying the pointer in the main function, only the local function pointer, as such, it would have no effects on the one in main.
Here's the edited version:
int read(char ***a, int *len) {
int i;
scanf("%d", len);
if( *len <= 0 ) return 1;
(*a) = (char **) malloc(*len * sizeof(char *));
if((*a) == NULL) return 1;
for( i = 0; i < *len; i++ )
{
(*a)[i]=(char *)malloc(101*sizeof(char));
scanf("%s", (*a)[i]);
}
printf("Saved\n");
return 0;
}
int main() {
int i, n;
char **A;
if(read(&A, &n)) return 1;
printf("%d\n",n);
for( i = 0; i < n; i++ )
{
printf("printf\n");
printf("%s\n", A[i]);
}
return 0;
}
Upvotes: 1