Home > OS >  Why the content of a pointer to char can be a string but I can't scanf a pointer to char withou
Why the content of a pointer to char can be a string but I can't scanf a pointer to char withou

Time:02-28

Why is the first option OK but the second option should use dynamic memory and the first doesn't?

//first option
char *p = "hello";
//second option
char *p;
scanf("%s",p);
//and introduce hello on the terminal

CodePudding user response:

The pointer p in this declaration

//first option
char *p = "hello";

points to the first character of the string literal "hello" that is stored in memory as a character array of the type char[6].

You can imagine it the following way

char string_literal[] = "hello";
char *p = string_literal;

Only pay attention to that you may not change a string literal pointed to by a pointer. Any attempt to change a string literal results in undefined behavior. For example you may not write

char *p = "hello";
p[0] = 'H';

In this code snippet

//second option
char *p;
scanf("%s",p);

the pointer p is not initialized and has an indeterminate value. So the call of scanf invokes undefined behavior.

At least you could write for example

char s[6];
char *p = s;

scanf( "%s, p ); // or scanf( "%5s", p );

to enter the string "hello";

Or if to use sscanf referred in your comment to the question you could write

char s[6];
char *p = s;

sscanf( "hello", "%s", p );

CodePudding user response:

Because in the first case the compiler allocates (usually) memory for the string in "static" memory. So p is pointing to storage that contains the string constant.

The second case, p is uninitialized, and points to nothing. So you have to allocate memory for it. The alternative to using heap-based allocation is to define like

char p[100];
scanf("0s",p);

you are still allocating memory in this case, but on the stack. Either way, C strings (and pointers) need some valid memory area to point to, whether it is on the stack, heap, or static.

CodePudding user response:

To do what you want in the second case, you would need to do it like this:

char *p;

printf("Enter a word: ");
scanf("%ms",&p);
printf("User entered '%s'\n",p);
free(p);

The m option to %s (in scanf) tells scanf to allocate whatever memory is needed for the string. Read the scanf man-page for more details.

  • Related