我觉得串约总线错误的困惑(C) [英] I feel confusion about bus error in string (C)
问题描述
我觉得混淆互换两个人物在一个字符串C.
它工作得很好,当我把它设置为一个数组:
I feel confusion about the swap two characters in one string with C. It works well when I set it as an array:
字符strBase [8] =acbdefg;
在这种情况下,我可以换任何字符。
但它触发总线错误,当我将它设置为一个字符串:
in this case I could swap any character. But it trigger the bus error when I set it as a string:
的char * strBase =acbdefg;
非常感谢任何人都可以解释它,或者给我一些暗示!
Thanks a lot for anyone could explain it or give me some hint!
推荐答案
这里的不同之处在于
char *strBase = "acbdefg";
将放在 acbdefg
在内存中,使 strBase
一个指针,使得只读部分在此内存非法任何写入操作。
will place acbdefg
in the read-only parts of the memory and making strBase
a pointer to that, making any writing operation on this memory illegal.
它没有名字,并具有静态存储时间(这意味着它所处的程序的整个生命);和
类型指针到字符,名为 strBase
,这是初始化第一个字符在该无名,只读阵列的位置。
It has no name and has static storage duration (meaning that it lives for the entire life of the program); and
a variable of type pointer-to-char, called strBase
, which is initialised with the location of the first character in that unnamed, read-only array.
虽然这样做:
char strBase[8] = "acbdefg";
把文字串在只读存储器和拷贝字符串新分配的堆栈上存储器。
puts the literal string in read-only memory and copies the string to newly allocated memory on the stack.
所以这个数组是在内存分配,并且它的生命有多长,取决于出现在哪里申报。如果声明是一个函数内,将活直到它被声明在,而且几乎可以肯定在栈上分配的块的末端;如果它是一个功能之外,它可能会被存储在从可执行文件加载到写入内存能够在程序运行时初始化的数据段之内。
So this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialized data segment" that is loaded from the executable file into write able memory when the program is run.
制作
strBase[0] = 'x';
合法的。
这篇关于我觉得串约总线错误的困惑(C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!