我不知道什么是动态分配内存的正确方法:
我有一个.csv文件,大约有50行,我需要在内存中分配足够的空间来将文件的每一行保存在结构向量的一个空间中。
另外,我知道malloc的返回是分配的内存空间的第一个位置。
例子:
typedef struct{
int a;
float b;
char name[10]; //This will be set dynamically too, later...
}my_struct;
int main(){
int *p_array;
size_t vector_size = 2; //Same as doing: my_struct struc[2] ?
p_array = (int *) malloc(vector_size * (int));
my_struct struc[p_array];
return 0;
}
对吗?如果不是的话,那就是正确的方法。我没有错,但我不知道为什么看起来不对。
最佳答案
完全错了,从这里开始
这是错误的
p_array = (int *) malloc(vector_size * (int));
/* ^ what is this? */
如果需要
vector_size
大小的整数数组,则需要 p_array = malloc(vector_size * sizeof(int));
/* ^ the sizeof operator */
这完全没有道理
my_struct struc[p_array];
也许你是说?
my_struct struc[vector_size];
在上面,您传递的是一个指针,一个整数应该放在哪里,如果这是编译的话,那么发生的情况是指针中存储的地址被计算为一个整数,因此您的
struc
数组的大小与您认为的非常不同如果您使用正确的版本,那么
malloc()
完全没有意义,因此您并不真正需要它。如果要动态分配
struc
数组,则my_struct *array;
array = malloc(elementCount * sizeof(my_struct)):
if (array == NULL)
pleaseDoNot_Use_array_AndProbably_AbortHere();
/* you can use it here, and when you finish */
free(array);
如果启用编译器警告,则会出现一些警告,这些警告会让您了解我上面提到的一些内容。
另外,在cThere is no need to cast
malloc()