[英]String - Segmentation Fault
我對此代碼有疑問。 我正在使用gcc編譯器,當我編譯並執行此代碼時,出現段錯誤。 我只是分配兩個變量,name_1作為指針,name_2作為字符串。 當我嘗試為兩個值提供字符串輸入時,出現段錯誤。 此段錯誤始終與我使用的指針變量相關聯。
在下面,我提供了錯誤的代碼和屏幕截圖。
#include <stdio.h>
int main()
{
char *name_1 ;
char name_2[10] ;
/* Getting 2 strings as an input from the user
and is stored in the pointer variable name_1 and name_2*/
scanf("%s",name_1) ;
scanf("%s",name_2) ;
/* Printing the values of the varibales
name_1 and name_2 in string format */
printf("\n%s",name_1) ;
printf("\n%s",name_2) ;
printf("\n\n") ;
return 0 ;
}
請幫助我在這段代碼。
char *name_1;
,是一個指針。 最初,它指向一些隨機垃圾。 然后,您要求scanf
在程序啟動時碰巧指向的隨機垃圾地址name_1
處放置一個字符串。 這是未定義的行為。 如果需要,一致的C實現可以僅在星期二使此程序按預期工作。 :)
如果要傳遞指針,則必須確保它首先指向有效的緩沖區。
此外,在對scanf
的調用中存在一定程度的間接沖突name_1
已經是一個指針。 您不想將指針傳遞給scanf
指針; 只是一個指針。
該問題的原始版本包含:
char *name_1;
...
scanf("%s", &name_1);
此后,該問題已修訂為包含:
char *name_1;
...
scanf("%s", name_1);
您尚未分配任何空間供name_1
指向。 您還以%s
格式將char **
(即&name_1
)傳遞給scanf()
,期望該格式為char *
。
可能的解決方法:
int main(void)
{
char name_1[20];
char name_2[10];
scanf("%s", name_1);
scanf("%s", name_2);
另一個可能的解決方法:
int main(void)
{
char name_0[20];
char *name_1 = name_0;
char name_2[20];
scanf("%s", name_1);
scanf("%s", name_2);
char *name_1 ;
...
scanf("%s",&name_1) ;
name_1
是一個懸空指針,您正在嘗試使用它,這是不正確的。
您的指針char *name_1
應該指向某個東西。 通常遵循
Declaring a pointer variable does not create the type of variable,
it points at. It creates a pointer variable. So in case you are pointing
to a string buffer you need to specify the character array and a buffer
pointer and point to the address of the character array.
建議更改:
您可以將char *name_1
指向另一個字符數組,或者
您可以將其作為數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.