动态分配结构向量内存
Allocate struct vector memory dynamically
不知道动态分配内存的正确方法是什么:
我有一个 .csv 文件,大约有 50 行,我需要在内存中分配足够的 space 来保存文件中的一个 space 结构向量。
另外,我知道malloc的return是分配内存的第一个位置space.
示例:
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);
如果启用编译器警告,将会出现一些警告,让您了解我上面提到的一些事情。
此外,在 c There is no need to cast malloc()
不知道动态分配内存的正确方法是什么:
我有一个 .csv 文件,大约有 50 行,我需要在内存中分配足够的 space 来保存文件中的一个 space 结构向量。
另外,我知道malloc的return是分配内存的第一个位置space.
示例:
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);
如果启用编译器警告,将会出现一些警告,让您了解我上面提到的一些事情。
此外,在 c There is no need to cast malloc()