简体   繁体   中英

C program. Taking string input to char pointer problem

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 ?

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) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM