1

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);

Im getting this kinda errors:

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 ?

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 1
    Leave off the `&` in the `scanf` calls. `scanf("%s",...)` wants a `char *` which is `srchstr` but `&srchstr` is `char **`. So ... `scanf("%255s",srchstr);` – Craig Estey Apr 22 '20 at 23:33
  • `fflush(stdin)` is undefined behavior, i.e. don't do that. Instead of `scanf`, use `fgets` to read a line of input, and use `strcspn` to [remove the newline that `fgets` puts in the buffer](https://stackoverflow.com/a/28462221/3386109). – user3386109 Apr 22 '20 at 23:40

1 Answers1

1

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) {}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • @PatrykPiwowarczyk, I'm glad I could help, don't forget to [accept the answer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) if you think it correctly addresses your problem. – anastaciu Apr 24 '20 at 12:18