Declare an array manually VS malloc or calloc an array
用英文是因为有些东西得用他们的语言才能表达不失真
栈和堆
In C, a heap is a region of memory that is dynamically allocated during runtime. It is used to store variables and data structures that have a longer lifetime than the function call that created them.The stack, on the other hand, is a region of memory that is used for function call frames and local variables. It is managed automatically by the CPU and memory management unit, and is typically much faster to allocate and deallocate memory from than the heap.When to use the heap instead of the stack depends on the specific use case. If the data structure or variable needs to have a longer lifetime than the function call that created it, or if the amount of memory needed is not known at compile time, then the heap is a better choice.On the other hand, if the data structure or variable has a short lifetime and the amount of memory needed is known at compile time, then the stack is a better choice as it is faster and more memory-efficient.
我们在main声明一个数组叫a,可以说this is a static array
=> 在栈中main scope里把开辟一片连续的内存交给a,a是一片内存
而用malloc或者calloc开辟数组是用指针指向堆一块内存区域,并且要注意的是一开始具体指向的就是第一个数据,所谓的它能指向一片区域是因为数据存放在一起的,移动指针可以到下一个
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = (int*)malloc(sizeof(int)*10);
printf("%d\n", sizeof(int));
printf("arr: %p\narr + 1: %p\n&arr: %p\n&arr + 1: %p\n",arr, arr+1, &arr, &arr+1);
printf("%d\n", sizeof(arr)/sizeof(arr[0]));
int a[5] = {1, 2, 3, 4, 5};
printf("a: %p\na + 1: %p\n&a: %p\n&a + 1: %p\n",a, a+1, &a, &a+1);
printf("%d\n", sizeof(a)/sizeof(a[0]));
return 0;
}
sizeof是运算符,本质是通过偏转量来确定字节数 => sizeof(a) == (a + 1) - a
前面说过数组名a代表的是一片内存,如果它+1的话得到的是下一片内存的地址啦
做差不就是这篇内存的总字节数吗?再除以int的单位字节数就是这个数组的长度
但是malloc或calloc出来的数组不能通过这种方法来获取数组长度
因为他们有本质区别:malloc的arr是一个指针,sizeof(arr)得到的就是arr指针的大小,并不是一整片int数据所在的内存总字节数
想其他函数传数组也一样,其实是用指针接受从main scope传来的数组首地址,用sizeof获取数组长度同样不科学
=> 要想用sizeof获取数组长度仅限于在同一scope中declare 的 a static array
文章来源:https://www.toymoban.com/news/detail-491971.html
字符数组以及字符串常量
挖个坑,以后有空再来填上
文章来源地址https://www.toymoban.com/news/detail-491971.html
到了这里,关于C进阶 - 数组和指针的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!