Reputation: 97
Hello I have a problem with my C code. I'm trying to let user assign a string to a previously defined char *srchstr
; and char *repstr;
. By looking at other similar threads I've tried implementing it in the following way but it still fails:
char *srchstr;
srchstr = malloc(256);
char *repstr;
repstr = malloc(256);
printf("what are you searching for?:");
scanf("%255s",&srchstr);
fflush(stdin);
printf("\n what do you want to replace it with?:");
scanf("%255s",&repstr);
The whole idea behind the program was to give user ability to chose what text he wants to replace with what (whole code works just fine with srchstr
and repstr
defined in code but i cannot implement user input)
this is how it looked like in the beggining:
char *srchstr = "400,300";
char *repstr = "400,300: (000,000,000) #000000";
How can I fix it so user can type in the srchstr
and repstr
?
Upvotes: 1
Views: 244
Reputation: 23802
scanf("%255s",&srchstr);
->
scanf("%255s", srchstr);
scanf("%255s",&repstr);
->
scanf("%255s",repstr);
The &
operator means you are passing the address of a given memory space, effectively a pointer the memory space in which to store the input, identified by a variable name, that would be fine because scanf
expects precisely that.
But since srchstr
and repstr
are already pointers, you are effectively passing the address of the pointers (pointers to the pointers) instead of the address of the memory space (pointers to the memory space) in which to store the input.
Side note:
fflush(stdin)
Invokes undefined behaviour, it's meant to be used with stdout
.
You can replace it with:
int c;
while((c = fgetc(stdin)) != '\n' && c != EOF) {}
Upvotes: 1