I'm trying to make a simple program that keeps reading strings from the standard input using scanf and putting them into an array of strings (Right now I'm just testing it using 3 words, hence only 3 print statements at the end). I'm able to keep reading until there are no more strings, however I've encountered a bug where after the looping is done, all the strings in the array are the last string read in. I've tried putting a print statement within the loop to debug, and it is reading in the correct string. However when the looping is finished, all the strings in the array are the last string read in. Can anyone point out where I'm going wrong here? Thanks.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int c = 0;
char** w_arr = malloc(3*sizeof(char*));
char* w = malloc(10*sizeof(char));
while (scanf("%s", w) == 1) {
w_arr[c] = w;
//printf("%s", w_arr[c]); debug print statement
c++;
}
printf("%s, %s, %s\n", w_arr[0], w_arr[1], w_arr[2]);
return 0;
}
malloca newwbuffer for everyscanf(or some other way of getting a new buffer such asw_arr[c]=strdup(w)). As it is, all your array entries point to the same buffer whose contents are being overwritten for everyscanf.w_arr[0]point to that space. Then you read the second string into that space, and makew_arr[1]point to that space. Then you read the third string into that space, and makew_arr[2]point to that space. The end result is thatw_arr[0],w_arr[1]andw_arr[2]all point to that space, and that space contains the third string (because you overwrote the first two).