C进阶 - 数组和指针

文章讨论了C语言中动态内存分配(堆)与栈的区别,解释了何时使用堆(如数组生命周期长或大小未知时)和栈(生命周期短且大小已知时)。提到了数组声明与malloc/calloc的区别,指出了用sizeof获取动态分配数组长度的局限性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

字符数组以及字符串常量

挖个坑,以后有空再来填上

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值