在char指针变量中更改char [英] Changing chars in char pointer variable
本文介绍了在char指针变量中更改char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更改char指针变量所指向的chars:
I am trying to change chars pointed to by a char pointer variable:
char *test3 = "mutable";
printf("Expected: mutable, Result: %s\n", test3);
testt(test3);
printf("Expected tutable, Result: %s\n", test3);
void testt(char *s) {
*s = 't'; // FAILS, I get Segmentation Fault Error
}
为什么上述方法不起作用?指针变量指向的字符是不可变的吗?如果是这样,我将如何修改指针变量的内容?
Why does the above approach not work? Are chars pointed to by pointer variables immutable? If so, how would I modify the contents of the pointer variable?
推荐答案
这是因为您的char *
指向字符串文字,并且字符串文字几乎位于只读存储器中的所有现代OS中.
That is because your char *
points to a string literal and string literals are in almost every modern OS located in read-only storage.
尝试将其复制到堆栈中:
Try copying it onto the stack:
char test3[] = "mutable";
这篇关于在char指针变量中更改char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文