-1

我对用 C 交换一个字符串中的两个字符感到困惑。当我将它设置为数组时效果很好:

char strBase[8] = "acbdefg";

在这种情况下,我可以交换任何字符。但是当我将其设置为字符串时会触发总线错误:

char *strBase = "acbdefg";

非常感谢任何人可以解释它或给我一些提示!

4

3 回答 3

7

The difference here is that

 char *strBase = "acbdefg"; 

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.

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.

While doing:

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.

Making

strBase[0] = 'x';

legal.

于 2014-03-28T03:58:52.987 回答
2

Your problem is one of memory allocation. You need space to store your characters. When you wrote:

char strBase[8] = "acbdefg";

you created automatic storage (often called the stack) and initialized it with a string of characters. But when you wrote:

char *strBase = "acbdefg";

you created a pointer and pointed it at a constant string. The compiler puts that in a part of memory that is marked as read-only. If you try to change that it will result in a memory access violation.

Instead you could do something like:

const char* strData = "acbdefg";
int size = 1024;
char *strBase = (char*)malloc(size);
strncpy(strBase, strData, size);
ProcessString(strBase);
free(strBase);
于 2014-03-28T03:55:48.510 回答
0

最可能的原因是

char strBase[8] = "abcdefg";

使编译器为八字符数组保留内存,并使用值“abcdefg\0”对其进行初始化。相比之下,

char *strBase = "abcdefg";

只为指针保留内存,用字符串的地址初始化。"abcdefg" 是一个常量字符串,因此,编译器将它存储在一段被标记为只读的内存中。尝试修改只读内存会导致 CPU 故障。

你的编译器应该在第二种情况下给你一个关于 const mismatch 的警告。或者,您的编译器可能具有更改常量字符串的只读性的设置。

于 2014-03-28T03:47:10.527 回答