我如何为该2d数组动态分配空间有什么问题? [英] What is wrong with how I'm dynamically allocating space for this 2d array?

查看:83
本文介绍了我如何为该2d数组动态分配空间有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个2D数组,该数组将能够存储.txt文件的每个字符作为2D数组中的元素.

I'm trying to create a 2D array that will store be able to store each character of a .txt file as an element in the 2D array.

如何为它动态分配空间?

How do I dynamically allocate space for it?

到目前为止,我已经完成了分配它的工作. (这是GeeksForGeeks的副本)

This what I've done so far to malloc it. (this was copied of GeeksForGeeks)

char *arr[rownum2];

for (i = 0; i < rownum2; i++) {
    arr[i] = (char *)malloc(colnum * sizeof(char));

但是,我认为这是稍后程序中与内存相关的严重问题的根源,并且我也被告知其中的某些部分是不必要的.

However, I think this is the source of serious memory related issues later on in my program, and I've also been told some parts of this are unnecessary.

在这种特定情况下,能否请我获得最合适的方法为2D阵列动态分配内存?

Can I please get the most suitable way to dynamically allocate memory for the 2D array in this specific scenario?

推荐答案

您发布的代码为"OK",只要您记得稍后在代码中调用分配的内存上的free(),如下所示:

The code you have posted is 'OK', so long as you remember to call free() on the allocated memory, later in your code, like this:

for (i=0;i<rownum2;i++) free(arr[i]);

...而且我也被告知其中的某些部分是不必要的.

...and I've also been told some parts of this are unnecessary.

无需显式强制转换,因此,代替:

arr[i] =  (char *)malloc(colnum*sizeof(char));

只需使用:

arr[i] =  malloc(colnum*sizeof(char));

严格来讲,sizeof(char)也是不必要的(char的大小始终为1),但是为了清楚起见,您可以保留它.

The sizeof(char) is also, strictly speaking, unnecessary (char will always have a size of 1) but you can leave that, for clarity.

这篇关于我如何为该2d数组动态分配空间有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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