使用指针知道数组的大小 [英] Knowing the size of the array using pointer

查看:66
本文介绍了使用指针知道数组的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用通过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.

这篇关于使用指针知道数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆