使用指针知道数组的大小

编程入门 行业动态 更新时间:2024-10-24 16:27:40
本文介绍了使用指针知道数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何使用通过malloc分配的指针来知道数组的大小?

How can i know the size of the array using a pointer that is allocated using malloc?

#include <stdio.h> int main(){ int *ptr = (int *)malloc(sizeof(int * 10)); printf("Size:%d",sizeof(ptr)); free(ptr_one); return 0; }

在这种情况下,我仅得到指针的大小为8.如何修改代码以获取数组的大小为40.

I get only the size of the pointer in this case which is 8.How to modify the code to get the size of array which will be 40.

推荐答案

您不能. 您将需要进行簿记并自己进行跟踪.使用new,您可以分配动态内存,而在分配内存时,您只需调用delete,它就知道它已经分配了多少内存,因为该语言在内部进行处理,因此用户无需费心记账.如果仍然需要它,则需要通过单独的变量进行跟踪.

You cannot. You will need to do the bookkeeping and keep track of it yourself. With new you allocate dynamic memory and while deallocating the memory you just call delete, which knows how much memory it has deallocate because the language takes care of it internally so that users do not need to bother about the bookkeeping. If you still need it explicitly then you need to track it through separate variable.

更多推荐

使用指针知道数组的大小

本文发布于:2023-07-29 00:49:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235710.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   指针   大小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!