#define OK 0
#define MAXSTRING 200
#define NUMBER 10
#define MALLOC_ERROR 2
int main(int argc, char** argv) {
char **B = (char**)malloc(sizeof(char*)*NUMBER);
char buffer[MAXSTRING];
int i, strings = 0, arraysize = NUMBER;
if (( B = ( char**)malloc(sizeof(char*)*NUMBER))==NULL) {
printf("initial malloc error\n");
fflush(stdout);
exit(MALLOC_ERROR);
}
for(int i = 0; i< NUMBER; i++) {
B[i] = (char*)malloc(sizeof(char)*MAXSTRING);
}
while((fgets(buffer,MAXSTRING,stdin))!=NULL) {
/*
if(strings+1>arraysize)
{
arraysize = 2*arraysize;
B=realloc(B,(arraysize)*sizeof(char*));
}
*/
buffer[strlen(buffer)-1]='\0';
B[strings] = buffer;
printf("%s \n", buffer);
strings++;
}
printf("Read %d strings:\n", strings);
for (i = 0; i<strings ; i++) {
printf("\t%s\t %d\n", B[i], (int)strlen(B[i]));
}
return 0;
}
When i tried to print the B[i] from the loop,it just outputs the last input of the stdin in all of its positions. I tried testing with normal for loop and it somehow works, but i do not know the cause of the problem. Thanks for the help!! For example, i put "giraffe" as first input, another input "eat", last input"leaves", the loop of B[i] only outputs "leaves"