char* s1 = "";

Asked 1 weeks ago, Updated 1 weeks ago, 0 views

I'd like to receive a string and save it.

int main(void){ char * s1 = "";
scanf("%s", s1); }

Why do I get an error if I write it like this? Is it because of the wrong initialization of the string? (+I know that s1 is the pointer that stores the address value where the string is stored, is that right?)


2022-09-20 10:55

1 Answers

String constants are typically stored in read-only memory.

char * s1 = "";

Thus, the string constant " of the above code is stored in read-only memory, and its starting address is stored in s1. Because it is a read-only memory, the value cannot be saved to that address through the scanf function, etc.

To do what you want to do in the question, you need to declare a char array of sufficient length and take input using the starting address of the array.

char s1[80] = { 0 };
scanf("%s", s1);

2022-09-20 10:55

If you have any answers or tips

© 2022 pinfo. All rights reserved.