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 ?

2
  • 1
    Leave off the & in the scanf calls. scanf("%s",...) wants a char * which is srchstr but &srchstr is char **. So ... scanf("%255s",srchstr); Commented Apr 22, 2020 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. Commented Apr 22, 2020 at 23:40

1 Answer 1

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) {}
Sign up to request clarification or add additional context in comments.

1 Comment

@PatrykPiwowarczyk, I'm glad I could help, don't forget to accept the answer if you think it correctly addresses your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.