boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 这个怎么allocate memory?
相关主题
在子函数内开内存,返回主函数指针然后释放空间是不是很糟糕的(转载)
c的问题(2)
ask a c question
array allocation in c
size不固定的struct怎么定义呀?
a=(char **)malloc(12*sizeof(char *)) 是什么意思?
再问一个free()的问题
问个程序问题
问个hash函数问题
C++ Interview Question
相关话题的讨论汇总
话题: int话题: myarray话题: nrows话题: allocate话题: memory
进入Programming版参与讨论
1 (共1页)
o********7
发帖数: 154
1
有一个integer 2D array, column是2列, row的数目不确定, 是从function的参数传
过来的,大小是nrows, 这个array大概的样子就是 myArray[][2]
如何在C中allocate memory呢?我用了下面的编译不过
int (*myArray)[2] = malloc(nrows*sizeof(int[2]));
A**u
发帖数: 2458
2
2 * nrows * sizeof(int)
int[2] 不是type

【在 o********7 的大作中提到】
: 有一个integer 2D array, column是2列, row的数目不确定, 是从function的参数传
: 过来的,大小是nrows, 这个array大概的样子就是 myArray[][2]
: 如何在C中allocate memory呢?我用了下面的编译不过
: int (*myArray)[2] = malloc(nrows*sizeof(int[2]));

a***y
发帖数: 2803
3
int** myArray;
myArray = (int**) malloc(nrows * sizeof(int*));
for (int i = 0; i < nrows; i++)
myArray[i] = (int*) malloc(2 * sizeof(int));

【在 o********7 的大作中提到】
: 有一个integer 2D array, column是2列, row的数目不确定, 是从function的参数传
: 过来的,大小是nrows, 这个array大概的样子就是 myArray[][2]
: 如何在C中allocate memory呢?我用了下面的编译不过
: int (*myArray)[2] = malloc(nrows*sizeof(int[2]));

t****t
发帖数: 6806
4
事实上, 原来的写法没有问题, 应该是可以通过的. int[2]是一个type, sizeof(int[2
])也没有问题.
但是如果用C++编译器(或者源文件后缀是.cpp/.C/.cxx之类), 需要作强制转换, 因为
malloc返回的是void*:
int (*myArray)[2] = (int(*)[2])malloc(nrows*sizeof(int[2]));

【在 A**u 的大作中提到】
: 2 * nrows * sizeof(int)
: int[2] 不是type

t****t
发帖数: 6806
5
你这个根本就不合楼主的要求.

【在 a***y 的大作中提到】
: int** myArray;
: myArray = (int**) malloc(nrows * sizeof(int*));
: for (int i = 0; i < nrows; i++)
: myArray[i] = (int*) malloc(2 * sizeof(int));

o********7
发帖数: 154
6
这个是正解, 非常感谢。
我正是用的c++ compiler, 所以出错误了。

[2

【在 t****t 的大作中提到】
: 事实上, 原来的写法没有问题, 应该是可以通过的. int[2]是一个type, sizeof(int[2
: ])也没有问题.
: 但是如果用C++编译器(或者源文件后缀是.cpp/.C/.cxx之类), 需要作强制转换, 因为
: malloc返回的是void*:
: int (*myArray)[2] = (int(*)[2])malloc(nrows*sizeof(int[2]));

j*a
发帖数: 14423
7
下次好歹把出错信息列一列

【在 o********7 的大作中提到】
: 这个是正解, 非常感谢。
: 我正是用的c++ compiler, 所以出错误了。
:
: [2

A**u
发帖数: 2458
8
都大牛啊

[2

【在 t****t 的大作中提到】
: 事实上, 原来的写法没有问题, 应该是可以通过的. int[2]是一个type, sizeof(int[2
: ])也没有问题.
: 但是如果用C++编译器(或者源文件后缀是.cpp/.C/.cxx之类), 需要作强制转换, 因为
: malloc返回的是void*:
: int (*myArray)[2] = (int(*)[2])malloc(nrows*sizeof(int[2]));

1 (共1页)
进入Programming版参与讨论
相关主题
C++ Interview Question
什么是OS Memory management and heap structure?
数组定义的时候,分配空间了么?
ask a simple question about int pointer.
C里面一个被分配了内存的指针如何知道分配了多少?
菜鸟问个C++问题
问个简单的memory allocation 的问题。
VC++ 中的 memory leak problem
a weak c question, how to pass an array into a function?
[合集] 谁给个stack-based allocation 的C++的例子?
相关话题的讨论汇总
话题: int话题: myarray话题: nrows话题: allocate话题: memory