簡體   English   中英

C中這兩個指針賦值有什么區別?

[英]What is the difference between these two pointer assignments in C?

我一直在做很多研究,也玩過代碼,但我仍然對此感到困惑:為什么案例 1 會出錯?

情況1:

int arr[] = {0,4,7};
int *p = arr[0]; // pointer points to the first element in the array

printf("%d", ++*p);
// This results in Segmentation fault

案例2:

int arr[] = {0,4,7};
int *p = arr; // pointer points to the first element in the array

printf("%d", ++*p);
// This prints 1

在情況 1 中: arr[0]是一個int值。 int *p = arr[0]; 是一個錯誤。

C中這兩個指針賦值有什么區別?

首先,兩者的共同點是兩者都不是作業。

 int *p = arr[0]; // pointer points to the first element in the array

這里的評論是錯誤的。 arr是一個int數組。 arr[0]是該數組的第一個元素。 它是一個int int *p = arr[0]嘗試使用存儲在數組中的值初始化指針。 但是,類型不匹配,因為該值不是指針。 int不能隱式轉換為int* ,因此程序格式錯誤。

需要一個符合標准的語言實現來為您診斷這個問題。 這是我的編譯器所說的:

 error: invalid conversion from 'int' to 'int*'

為什么情況 1 會出錯?

如果程序甚至可以編譯,則您正在初始化一個值為 0 的指針。這可能意味着它是一個空指針並且它不指向任何對象。 ++*p嘗試通過這個空指針間接訪問不存在的整數。

 int *p = arr; // pointer points to the first element in the array

這里的評論是正確的。

我想它會拋出一個錯誤,因為在將值分配給指針之前沒有使用 '&' 。 因為它是一個指針,所以你不能給它賦值。 您只能使用它來存儲地址。 我用 C++ 編碼它,這是正確的形式。我想它有幫助。

#include <iostream>

using namespace std;

int main(){
  int arr[] = {0,4,7};
  int *p = &arr[0]; //you are missing '&' before array[0]

  printf("%d", ++*p);
  system("pause");
  // This prints 1
  }

暫無
暫無

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

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