Answer the question
In order to leave comments, you need to log in
Why does a string declared as a pointer to char not change, but as an array of char does it change?
Why, if you declare a string as an array, then the program works as expected, but if you declare a string as a pointer to char, then nothing works and the unchanged value is displayed?
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
void change_str(void(*fp)(char *), char * str);
void to_upper(char * str);
int main(int argc, char * argv[])
{
char str[] = "hello"; // char * str = "hello";
change_str(to_upper, str);
_getch();
return 0;
}
void change_str(void(*fp)(char *), char * str)
{
(*fp)(str);
puts(str);
}
void to_upper(char * str)
{
while (*str)
{
*str = toupper(*str);
str++;
}
}
Answer the question
In order to leave comments, you need to log in
Most likely because in the variant
char * str = "hello";
The string "hello" itself is stored in read-only memory, which is allocated by the OS for constants when the program is loaded into memory.
In the variant with an array, memory is allocated on the stack, so there is no problem with the change.
To move to a pointer, allocate memory dynamically and copy the string there. At the end, do not forget to free the memory.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question