第一个问题: 数组在 C 中是 LinkedList 吗? 不,数组和linkedList 是不同的。 LinkedList(相似/不同2数据类型的集合)可以有array(相似数据类型的集合)作为其中的一部分,但两者并不相同。
int nums[7] = {5,6,7,8,9,10,11};
这里nums 是一个由 7 个整数组成的数组,所有元素都存储在 连续 内存位置中,数组名称表示其基地址。让我们假设nums 起始地址是0x100 那么它看起来像
nums[0] nums[1] nums[2] nums[3] nums[4] nums[5] nums[6]
-------------------------------------------------------------------------
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
-------------------------------------------------------------------------
0x100 0x104 0x108 0x112 0x116 0x120 0x124
nums
LSB
接下来当语句int *n = &nums[3]; 执行时,n 是整数指针,它指向&nums[3],即0x112,如上所示。所以 n n[0] 是 0x112 而不是 0x100 如果你增加 n 它增加 4 个字节等等。
-----------
| 0x112 | <--- int *n = &nums[3]; /* n is pointer and it needs address and here & is unary operator and &num[3] is assigned to n */
----------
n
还有
---------------------------------------------------------------------
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
---------------------------------------------------------------------
0x100 0x104 0x108 0x112 0x116 0x120 0x124
| | | |
n[0] n[1] n[2] n[3]
根据您的问题,代码块
int *n = nums[3]; // I removed the & from &nums[3]
printf("n[0]=%d n[1]=%d n[2]=%d \n", n[0], n[1], n[2]);
这里n 指向8,它不是一个有效的地址,看起来像
---------
| 8 | <-- not that n is int pointer
---------
n
当您尝试打印n[0] 时,它会崩溃,因为您尝试打印地址8 处的值,这是无效地址,地址8 可能被保留用于其他目的,而不是为您的可执行文件@987654346 @。
n[0] = *(n + 0)
= *(8) = you are dereferencing invalid address which causes crash
还有
int *x = 50;
printf("X: %d",x) // it prints what X holds and that is 50
printf("X: %d", &x); /* &X means address of X, its an address not some long number , also use %p format specifier to print address. */
printf("X: %d", *x); /* this will cause crashes, as X points to invalid address
这里x 是一个整数指针,它应该使用有效地址进行初始化,例如
int var = 50;
int *x = &var; /* now x points to valid address */
printf(" value at the address : %d\n",*x);/* prints 50 */
最后我的建议是阅读一本好的 C 书籍并很好地理解数组和指针章节。