C 中的陣列實際上是常量指標。 指向陣列第一個元素的指標是一個常量。因此,似乎不可能為陣列指標分配地址值。
但在某些情況下,讓兩個陣列指向記憶體中的同一位置可能很有用。
那么我怎樣才能讓兩個陣列以這種方式指向同一個位置:
int a[10];
int b[10];
a = b; // Not possible
下面的內容似乎是一個有效的解決方案。但是,還有其他選擇嗎?
int *a;
int *b;
int c[10];
a = c; // If you change the value "a" points to
b = c; // it will be observed on "b"
a[2] = 5;
printf("Output is %d", b[2]);
>> Output is 5
uj5u.com熱心網友回復:
陣列的行為類似于指向其第一個元素的指標,但您不能重新分配它們:
int a[] = { 1, 2 };
int b[] = { 3, 4 };
b = a; // compilation error: b is constant
原因是它們的地址在編譯時已知,存盤在程式的只讀段中,寫入只讀段將是段錯誤。
指標是一種包含地址的型別,它可以在運行時分配。如果你在編譯時不知道你需要多少記憶體,你可以通過動態分配向你的系統詢問一些記憶體:
int * integers = malloc(sizeof(int) * 3); // dynamic array of size 3
// or
int * integers = malloc(sizeof(* integers) * 3);
如果你想讓 2 個陣列指向同一個記憶體:
char * interval1 = malloc(sizeof(char) * 2); // sizeof() useless here, char is defined as 1 byte
interval1[0] = 'A'; // equivalent to *(p 0) = 'A'
interval1[1] = 'Z'; // equivalent to *(p 1) = 'Z'
char * interval2 = interval1;
但如果兩個變數都在同一個函式中,興趣就相當有限。
我沒有添加檢查,但您應該始終在分配后檢查 NULL,并在不再需要記憶體時檢查 free()。
TDLR:如果您需要重新分配地址,請不要使用陣列型別,而應使用指標型別,它是動態的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/533419.html
標籤:数组C指针记忆内存管理
