如何在C中获取动态分配的二维数组的长度 [英] How to get the length of dynamically allocated two dimensional arrays in C

查看:262
本文介绍了如何在C中获取动态分配的二维数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是如何获取C中动态分配的2D数组的长度?我以为下面的代码应该获取行数,但事实并非如此.

char** lines;
/* memory allocation and data manipulation */

int length; //the number of rows

length = sizeof(lines)/sizeof(char*);

对此有何想法?

解决方案

您无法获得用C(2D或其他方式)动态分配的数组的长度.如果您需要该信息,则在最初分配内存时将其保存到变量中(或至少使用一种计算方式),然后将指针传递给内存以及内存的大小.

在高于sizeof的测试用例中,返回的是lines类型的大小,因此您的长度计算等效于sizeof(char**)/sizeof(char*),并且很可能总是得到1的琐碎结果. /p>

The question is how to get the length of dynamically allocated 2D Arrays in C? I thought the code below should get the number of rows, but it doesn't.

char** lines;
/* memory allocation and data manipulation */

int length; //the number of rows

length = sizeof(lines)/sizeof(char*);

Any thoughts on this?

解决方案

You can't get the length of dynamically allocated arrays in C (2D or otherwise). If you need that information save it to a variable (or at least a way to calculate it) when the memory is initially allocated and pass the pointer to the memory and the size of the memory around together.

In your test case above sizeof is returning the size of the type of lines, and thus your length calculation is equivalent to sizeof(char**)/sizeof(char*) and is likely to have the trivial result of 1, always.

这篇关于如何在C中获取动态分配的二维数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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