char *p="This is anonymous string literal";
Doing this I can access this string easily but tell me that how can I get string literal from user using this p
pointer without declaring the other variable for string. Check my images from button to top.
CodePudding user response:
A string literal declares a const
character array. That means that any try to change the characters through the p
pointer would invoke Undefined Behaviour (the hell for C programmers...).
To be able to read a string from the user (note, not a literal one), you must either declare a character array, or allocate one with malloc
and friends.
Examples:
char str[80];
char *p = str; // Ok, you can do what you want with 79 charactes (last should be null)
or
char *p = malloc(80); // again 80 characters to play with
...
free(p); // but you are responsable for releasing allocated memory when done
CodePudding user response:
Changing the size of your string requires memory allocation.
Maybe you could just use a pointer to this string in your program and change the target of the pointer.
That may not answer your question but it can be interesting.
char *str = "My string";
char *str2 = "My string 2";
char **ptr = &str;
printf("%s\n", *ptr);
ptr = &str2;
printf("%s\n", *ptr);
Edit
From gets() documentation:
str − This is the pointer to an array of chars where the C string is stored
Means that the pointer passed as parameters of gets() must already have allocated memory, you could try:
char p[50];
// instead of
char *p; // No memory allocated to put user input in
That's why you got a segfault (with memory observation tools like valgrind you'll see errors on all compilers).
Also printf() is not flushing the output without a carriage return (\n), you could try:
printf("No carriage return");
fflush(stdout); // Force stdout update