4
我寫了一個小函數foo
,它改變了一個字符串。分段錯誤SIGSEGV依賴於初始化方法
當我使用該函數時,有時會收到一個SIGSEGV錯誤。這取決於字符串如何初始化。在調用函數main
中,通過內存分配初始化字符串並調用strcpy
。我可以正確更改該字符串。
另一個字符串(TestString2
)在我聲明變量時被初始化。我無法修剪這個字符串,但得到了SIGSEGV錯誤。
這是爲什麼?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void foo(char *Expr)
{
*Expr = 'a';
}
int main()
{
char *TestString1;
char *TestString2 = "test ";
TestString1 = malloc (sizeof(char) * 100);
strcpy(TestString1, "test ");
foo(TestString1);
foo(TestString2);
return 0;
}
C沒有字符串類型。而指針不是一個數組! – Olaf
@xing,Re「* TestString2指向字符串*」,不,它指向一個字符串。字符串[文字](https://en.wikipedia.org/wiki/Literal_(computer_programming))是表示字符串的源代碼。 – ikegami