I’m having a segmentation fault when I want to save a string in a dynamic array.
I have a program that does this:
User insert char “s”
The program enters a loop and save strings in an array (name: cod).
When user inserts char “t”, it stops
After that I save that array in the first position of a new dynamic array (name: vec).
Then if user insert char “s” again
The program enters a loop and save strings in an array.
When user inserts char “t”, it stops
After that I save that array in the second position of a new dynamic array.
and so one.
This is my code:
int main(){
char Cod[30][11];
char tmp[11];
char ***vec;
int i = 0;
strcpy (tmp, "p");
vec = (char *** ) malloc (sizeof ( char *) );
vec[0] = (char ** ) malloc (sizeof ( char *) * 30);
do {
scanf("%s", tmp);
while( (strcmp (tmp, "p")) != 0){
strcpy ( Cod[i] , tmp );
scanf("%s", tmp);
i++;
}
vec = (char ***) realloc (vec, sizeof ( char *) * (i + 1));
vec[i + 1] = (char ** ) realloc (vec[i + 1], sizeof ( char *) * (30));
vec[i-1] = (char **) Cod;
scanf("%s", tmp);
}
while((strcmp (tmp, "s")) == 0);
printf("%s", vec[0][0]);
return 0;
}
This is the part of the code that work’s:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char Cod[30][11];
char tmp[11];
int i = 0;
strcpy (tmp, "p");
do {
scanf("%s", tmp);
while( (strcmp (tmp, "p")) != 0){
strcpy ( Cod[i] , tmp );
scanf("%s", tmp);
i++;
}
scanf("%s", tmp);
}
while((strcmp (tmp, "s")) == 0);
printf("%s", Cod[0]);
return 0;
}
Since it is a homework I tried to rewrite your code in something that should work…