typedef struct node {
int value;
struct node* next;
}node;
int* to_array (node* ll, int size) {
int i = 0;
int* arr = malloc(size*sizeof(int));
while (ll) {
arr[i] = ll->value;
ll = ll->next;
i++;
}
return arr;
}
谁能解释一下原因
int* arr = malloc(size);
会给我们一个数组?我认为当我们有指针时,我们不能像 arr[i] = 5
之类的那样单独更改它。
最佳答案
你的问题其实很好。当然,已经在 SO 上多次被询问和回答。但这仍然是一个好问题。
来自 C/C++ 常见问题解答:
http://c-faq.com/~scs/cgi-bin/faqcat.cgi?sec=aryptr
Arrays are not pointers, though they are closely related (see question 6.3) and can be used similarly (see questions 4.1, 6.8, 6.10, and 6.14).
当您声明一个数组(例如
int a[5]
)时,您已经为五个“int”元素分配了存储空间。您可以像a[i]
一样访问每个元素。当您声明一个指针(例如
int *b
)时,您还没有分配任何存储空间。您可以同时声明和初始化一个指针:
int *b = NULL; /* Initialize to 0 */ ... OR ... int *b = malloc (5 * sizeof (int)); /* Allocate storage for 5 "int" elements */
当您声明数组
a
时,您从栈中分配了空间。分配不能更改。当您声明
b
时,您分配了 SAME 空间量,但是您是从堆中分配的。此外,您可以随时更改b
以指向其他任何内容。您还可以realloc()
内存来更改存储空间的大小。正如您可以使用索引语法
a[i]
一样,您也可以使用完全相同的语法b[i]
。
此链接可能有助于解释:http://www.geeksforgeeks.org/g-fact-5/
附言:
当您“有指示”时,您绝对可以“单独更改它,例如 arr[i] = 5
或其他内容”。
关于c - 结构化链表到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230126/