簡體   English   中英

strcpy給段錯誤

[英]strcpy giving seg fault

我正在嘗試通過標准輸入創建用戶輸入的字符串數組,並對strcpy遇到麻煩。 假設用戶輸入了一個字符串,我想將其放在字符串數組的索引0處,這就是我正在做的

// Assuming the user won't input anymore than 100 characters
char input[100];
char temp[100];
char buffer[100];
char *array_of_strings[1];

if(fgets(buffer, 100, stdin) != NULL){
sscanf(buffer, "%s", temp);
strcpy(array_of_strings[0], temp);
}

我執行strcpy時就遇到了細分錯誤,但我不知道為什么。 我究竟做錯了什么?

array_of_strings是一個數組,其單個元素是char*指針。 char* 可能指向一個字符串,但是您必須以某種方式分配內存以包含該字符串。

strcpy(array_of_strings[0], temp);

array_of_strings[0]未初始化的指針。 將其作為第一個參數傳遞給strcpy()具有未定義的行為。 它可能(試圖)破壞其垃圾值恰好指向的任何內存塊,或者,如果幸運的話,您的內存管理系統將捕獲該錯誤並殺死您的程序。

解決此問題的一種方法是將array_of_strings定義為數組數組,而不是指針數組:

char array_of_strings[1][100];

另一種方法是使用malloc分配空間:

char *array_of_strings[1];
array_of_strings[0] = malloc(100);
if (array_of_strings[0] == NULL) {
    /* allocation failed take some corrective action */
}

array_of_strings[0]是一個指針,而不是數組。 因此,您無法使用malloc動態分配內存並使用array_of_strings[0]作為數組,或者無法將字符串復制到其中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM