我真的不明白為什么方法 1 有效但方法 2 無效。我真的不明白為什么它適用于字符而不是 int。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
/// WORK (METHODE 1)
char **string_array = malloc(sizeof(char **) * 10);
string_array[0] = "Hi there";
printf("%s\n", string_array[0]); /// -> Hi there
/// DOES NOT WORK (METHODE 2)
int **int_matrix = malloc(sizeof(int **) * 10);
int_matrix[0][0] = 1; // -> Segmentation fault
/// WORK (METHODE 3)
int **int_matrix2 = malloc(sizeof(int *));
for (int i = 0; i < 10; i )
{
int_matrix2[i] = malloc(sizeof(int));
}
int_matrix2[0][0] = 42;
printf("%d\n", int_matrix2[0][0]); // -> 42
}
uj5u.com熱心網友回復:
就型別而言,您希望從分配給它的指標為“上一級”型別分配記憶體。例如,一個int指標 (an int*) 指向一個或多個ints。這意味著,當你為它分配空間時,你應該根據int型別進行分配:
#define NUM_INTS 10
...
int* intPtr = malloc(NUM_INTS * sizeof(int));
// ^^ // we want ints, so allocate for sizeof(int)
在您的一種情況下,您有一個雙int指標 (an int**)。這必須指向一個或多個int指標(int*),所以這就是你需要為分配空間型別:
#define NUM_INT_PTRS 5
...
int** myDblIntPtr = malloc(NUM_INT_PTRS * sizeof(int*));
// ^^ "one level up" from int** is int*
但是,還有一種更好的方法可以做到這一點。您可以指定它指向的物件的大小而不是型別:
int* intPtr = malloc(NUM_INTS * sizeof(*intPtr));
這里,intPtr是一個int*型別,它指向的物件是 an int,這正是*intPtr給我們的。這具有減少維護的額外好處。假裝一段時間后,int* intPtr更改為int** intPtr. 對于第一種處理方式,您必須在兩個地方更改代碼:
int** intPtr = malloc(NUM_INTS * sizeof(int*));
// ^^ here ^^ and here
但是,使用第二種方式,您只需要更改宣告:
int** intPtr = malloc(NUM_INTS * sizeof(*intPtr));
// ^^ still changed here ^^ nothing to change here
隨著宣告從int*到的變化int**,*intPtr也“自動”變成了,從int到int*。這意味著范式:
T* myPtr = malloc(NUM_ITEMS * sizeof(*myPtr));
是首選,因為*myPtr無論是什么型別,都將始終參考我們需要為正確記憶體量調整大小的正確物件T。
uj5u.com熱心網友回復:
其他人已經回答了大部分問題,但我想我會添加一些插圖......
當您想要一個類似陣列的物件,即給定型別的一系列連續元素時T,您可以使用指向T,的指標T *,但您想要指向型別為 的物件T,這就是您必須分配記憶體的目的。
如果要分配 10 個T物件,則應使用malloc(10 * sizeof(T)). 如果您有一個將陣列分配給的指標,則可以從中獲取大小
T * ptr = malloc(10 * sizeof *ptr);
Here*ptr具有型別T,因此sizeof *ptr與 相同sizeof(T),但由于其他答案中解釋的原因,此語法更安全。
當你使用
T * ptr = malloc(10 * sizeof(T *));
您不會為 10 個T物件獲得記憶體,而是為 10 個T *物件獲得記憶體。如果sizeof(T*) >= sizeof(T)你很好,除了你浪費了一些記憶體,但如果sizeof(T*) < sizeof(T)你的記憶體比你需要的少。

您是否遇到此問題取決于您的物件和您所在的系統。在我的系統上,所有指標都具有相同的大小,即 8 個位元組,所以我是否分配并不重要
char **string_array = malloc(sizeof(char **) * 10);
或者
char **string_array = malloc(sizeof(char *) * 10);
或者如果我分配
int **int_matrix = malloc(sizeof(int **) * 10);
或者
int **int_matrix = malloc(sizeof(int *) * 10);
但它可能在其他架構上。
對于您的第三個解決方案,您遇到了不同的問題。當你分配
int **int_matrix2 = malloc(sizeof(int *));
您為單個int指標分配空間,但您立即將該記憶體視為有 10 個
for (int i = 0; i < 10; i )
{
int_matrix2[i] = malloc(sizeof(int));
}
您可以安全地分配給第一個元素,int_matrix2[0](但是我的方法存在問題);您寫入的以下 9 個地址不是您可以修改的。

下一個問題是,一旦你分配了矩陣的第一維,你就有了一個指標陣列。這些指標未初始化,大概指向記憶體中的隨機位置。

That isn't a problem yet; it doesn't do any harm that these pointers are pointing into the void. You can just point them to somewhere else. This is what you do with your char ** array. You point the first pointer in the array to a string, and it is happy to point there instead.

Once you have pointed the arrays somewhere safe, you can access the memory there. But you cannot safely dereference the pointers when they are not initialised. That is what you try to do with your integer array. At int_matrix[0] you have an uninitialised pointer. The type-system doesn't warn you about that, it can't, so you can easily compile code that modifies int_matrix[0][0], but if int_matrix[0] is pointing into the void, int_matrix[0][0] is not an address you can safely read or write. What happens if you try is undefined, but undefined is generally was way of saying that something bad will happen.

You can get what you want in several ways. The closest to what it looks like you are trying is to implement matrices as arrays of pointers to arrays of values.

There, you just have to remember to allocate the arrays for each row in your matrix as well.
#include <stdio.h>
#include <stdlib.h>
int **new_matrix(int n, int m)
{
int **matrix = malloc(n * sizeof *matrix);
for (int i = 0; i < n; i )
{
matrix[i] = malloc(m * sizeof *matrix[i]);
}
return matrix;
}
void init_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
matrix[i][j] = 10 * i j 1;
}
}
}
void print_matrix(int n, int m, int **matrix)
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int **matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
Here, each row can lie somewhere random in memory, but you can also put the row in contiguous memory, so you allocate all the memory in a single malloc and compute indices to get at the two-dimensional matrix structure.

Row i will start at offset i*m into this flat array, and index matrix[i,j] is at index matrix[i * m j].
#include <stdio.h>
#include <stdlib.h>
int *new_matrix(int n, int m)
{
int *matrix = malloc(n * m * sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
matrix[m * i j] = 10 * i j 1;
}
}
}
void print_matrix(int n, int m, int *matrix)
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
printf("%d ", matrix[m * i j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int *matrix = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
return 0;
}
With the exact same memory layout, you can also use multidimensional arrays. If you declare a matrix as int matrix[n][m] you will get what amounts to an array of length n where the objects in the arrays are integer arrays of length m, exactly as on the figure above.
If you just write that expression, you are putting the matrix on the stack (it has auto scope), but you can allocate such matrices as well if you use a pointer to int [m] arrays.
#include <stdio.h>
#include <stdlib.h>
void *new_matrix(int n, int m)
{
int(*matrix)[n][m] = malloc(sizeof *matrix);
return matrix;
}
void init_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
matrix[i][j] = 10 * i j 1;
}
}
}
void print_matrix(int n, int m, int matrix[static n][m])
{
for (int i = 0; i < n; i )
{
for (int j = 0; j < m; j )
{
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main(void)
{
int n = 3, m = 5;
int(*matrix)[m] = new_matrix(n, m);
init_matrix(n, m, matrix);
print_matrix(n, m, matrix);
int(*matrix2)[m] = new_matrix(2 * n, 3 * m);
init_matrix(2 * n, 3 * m, matrix2);
print_matrix(2 * n, 3 * m, matrix2);
return 0;
}
The new_matrix() function returns a void * because the return type cannot depend on the runtime arguments n and m, so I cannot return the right type.
Don't let the function types fool you, here. The functions that take a matrix[n][m] argument do not check if the matrix has the right dimensions. You can get a little type checking with pointers to arrays, but pointer decay will generally limit the checking. The last solution is really only different syntax for the previous one, and the arguments n and m determines how the (flat) memory that matrix points to is interpreted.
uj5u.com熱心網友回復:
方法 1 之所以有效,只是因為您使用字串文字“Hi there”的參考來分配char *陣列元素string_array。字串文字只是一個字符陣列。
嘗試:string_array[0][0] = 'a';它會失敗,并且您將取消參考未初始化的指標。
同樣發生在method 2.
方法 3. 為一個int值分配記憶體并將對它的參考存盤在陣列的 [0] 元素中。當指標參考有效物件時,您可以取消參考它 ( int_matrix2[0][0] = 42;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364036.html
