這個問題在這里已經有了答案: 為什么這個賦值不能在函式之外作業? (5 個回答) 11 小時前關閉。
#include<stdio.h>
int *a,b=9;
a=&b;
void main()
{
//nothing here
}
當我運行上面的代碼時,C我得到 5 個錯誤。他們是:-
1) [Warning] data definition has no type or storage class
2) [Warning] type defaults to 'int' in declaration of 'a' [-Wimplicit-int]
3) [Error] conflicting types for 'a'
4) [Note] previous definition of 'a' was here
5) [Warning] initialization of 'int' from 'int *' makes integer from pointer without a cast [-Wint-conversion]
編譯器將*a和a視為不同的變數,為什么?
但是,以下程式編譯時沒有任何錯誤:-
#include<stdio.h>
void main()
{
int *a,b=9;
a=&b;
}
請告訴我問題是什么?
uj5u.com熱心網友回復:
對于根據 C 標準的初學者,不帶引數的函式 main 應宣告為
int main( void )
你不能使用這樣的陳述
a=&b;
在檔案范圍內。您可以僅在檔案范圍內放置宣告。
你可以寫例如
int b=9, *a = &b;
uj5u.com熱心網友回復:
您的代碼無法編譯,因為在全域范圍內擁有代碼是非法的 - 特別是您的行a=&b是一個不在任何塊內的賦值運算式(例如您的 main 函式)。
出于這個確切原因,您的第二段代碼是合法的,并且可以按預期作業。
uj5u.com熱心網友回復:
請告訴我問題是什么?
問題是這樣的:
#include<stdio.h>
int *a,b=9;
a=&b; // <----- THIS IS YOUR PROBLEM (well, one of your problems)
void main()
{
//nothing here
}
你有賦值陳述句
a=&b;
在任何函式的主體之外,這是不允許的。您不能在檔案范圍內擁有陳述句。
您可以在檔案范圍內宣告,錯誤表明編譯器正試圖將該行解釋為 的另一個宣告a,但它失敗了,因為 a) 您已經宣告了a,并且 b) 較早的宣告是 type int *,而編譯器正試圖將這一秒宣告a為int(出于不值得討論的原因)。
像這樣的宣告
int b=9, *a=&b;
應該可以作業,但如果可以的話,請避免在檔案范圍內宣告內容。
uj5u.com熱心網友回復:
讓我們一一解決錯誤:
1) [Warning] data definition has no type or storage class
這指的是第二個a。這告訴我們它被解釋為第二個變數。
2) [Warning] type defaults to 'int' in declaration of 'a' [-Wimplicit-int]
這告訴我們變數被隱式宣告為 int 型別。此警告表示您缺少型別。因此你知道它是這樣讀的:
int *a,b=9;
int a=&b;
3) [Error] conflicting types for 'a'
這是錯誤:在第一行a定義為 a而在第二行定義為 a 。這是一個錯誤。int *int
4) [Note] previous definition of 'a' was here
這只是告訴我們之前的宣告在哪里a。
5) [Warning] initialization of 'int' from 'int *' makes integer from pointer without a cast [-Wint-conversion]
這是一個警告,因為您試圖將指標分配給int變數。
解決方案
解決方案是簡單地交換 a 和 b:
int b, * a=&b;
或者在兩條線上:
int b;
int * a=&b;
這也可以,但非常難看:
int *a,b=9;
int *a=&b;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/516679.html
標籤:C指针变量赋值外部的宣言
