簡體   English   中英

C 語言中的 int a[]、int *a1[] 和 int *a2 有什么區別?

[英]What is the difference between int a[], int *a1[], and int *a2 in C language?

我是 C 的新手,我正在學習指針和數組。 我的教授告訴我,我可以使用指針代替數組,反之亦然。 但是,在我編程的時候,我發現它們之間在用法上有一些區別。 例如,

int b[] = {1,2,3}; //I consider b as a pointer point to b[0]
int *ptr=b;
ptr++; //works well and point to 2
b++;  //I suppose it will point to b[1] but it doesn't work :(

這只是一個例子。 我對int a[]int *a1[]int *a2 (我知道基本概念)以及它們在 memory model 中的工作方式感到非常困惑? 指針/數組允許哪些語法(用法?)? (如上面的例子)
謝謝~

嗯... b是一個數組。 b++ 什么都不做。 它會返回一個錯誤,因為您正在遞增到一個不可變變量。
to the memory address of the array and by default ptr will point to the index of zero in the array b (being 1).因此,當您將指針ptr分配給數組b時,您將數組的 memory 地址,並且默認情況下ptr將指向數組b中的零索引(為 1)。
to the next index value that b holds in that index(ptr = b(which is also saying ptr = 0), b[0] = 1, ptr++, ptr = 1, b[1] = 2 etc..).因此,當您編寫ptr++時,您將索引號加一,然后ptrb在該索引中保存的下一個索引值(ptr = b(也就是 ptr = 0),b[0] = 1 , ptr++, ptr = 1, b[1] = 2 等等..)。
我希望這會有所幫助..

int b[] = {1,2,3};b的地址; 是不可變的(即不能更改)。 因此, b++等是非法的。

int a[]是一個int數組(僅包括一個int )。

int *a1[]是一個int *數組。 這可用於int arrays 的數組。

int *a2是指向int的指針。 這可以指向單個intint數組。

指針的概念和 arrays 差不多,但 arrays 有更多的約束。 數組包含 memory 中第一個元素的地址,但它是 const。 與任何其他 const 變量一樣,您不能將分配給數組的值更改為另一個數組(或同一數組的另一個索引)。

and about syntax, int *a2 is pointing to an int in the memory, doesn't matter just one integer, an element of an array or maybe point to block of memory in heap (that is allocated with malloc )

int a[]是數組的語法,數組是堆棧中 memory 的塊,不能更改或釋放或任何東西,它將在 scope 結束時釋放。

最后一個int *a1[]int*的數組類型,這意味着它可以包含int*類型的元素,並且每個int*可以指向 memory(4 字節)或另一個數組中的塊或單個 integer或者...

你也可以在這里閱讀它們: https://www.geeksforgeeks.org/difference-pointer-array-c/

暫無
暫無

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

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