我正在编写一个小程序来对字符串矩阵进行排序。在排序算法中,我使用此函数交换两个字符串,但在相同情况下,程序因 Segmentation Fault Error
而崩溃。我知道这是由我如何初始化 temp string
引起的,但我不明白为什么。
void stringSwap(char*string1,char*string2)
{ const int dim=sizeof(string1);
char temp[dim];
strcpy(temp,string1);
strcpy(string1,string2);
strcpy(string2,temp);
}
有人能解释一下为什么会出现这个错误吗?还有另一种模式可以在不使用我实际上不知道的动态分配的情况下正确地做这件事吗?非常感谢!
最佳答案
sizeof(string1)
是 4 或 8 个字节,具体取决于您的系统。
您应该改用 strlen(string1)+1
。
关于c - sizeof 作为字符串维度的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21738761/