#include <stdio.h>
int main(void)
{
int i,j,k;
char st;
printf("enter string\n");
scanf("%s", st);
printf("the entered string is %s\n", st);
}
編譯上面的程序給我一個警告的說法:格式 '%s' 的預期類型 '的char *'
warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]
palindrom.c:8:1: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'int' [-Wformat]
什麼我錯在這裏做什麼?
這是發生了什麼,當我運行它:
$ ./a.out
enter string
kiaaa
the entered string is (null)
編輯:
下面是代碼(由char st;
爲char *st
)的另一個版本:
#include <stdio.h>
int main(void)
{
int i,j,k;
char *st;
printf("enter string\n");
scanf("%s", st);
printf("the entered string is %s\n", st);
}
然而,它在運行時表現相同。
現在你的'char * st;'是一個未初始化的指針。你不知道它指向哪裏。在scanf中訪問它是未定義的行爲。您必須使其指向足夠大的有效內存塊。要麼聲明一個數組'char st [100];' - 當作爲參數傳遞給'scanf'或'printf'時,數組名將被轉換爲一個指針,所以很好 - 或者將它聲明爲一個指針,並在使用它之前分配一些內存,'st = malloc(100 * sizeof * st);'。你需要'#include'作爲'malloc',並檢查'malloc'是否返回NULL。 –