动态分配结构向量的内存
Allocate memory dynamically of a vector of struct
我无法通过 索引符号 在 主函数 中访问我的指针。我将指针作为参数传递给函数的方式对吗?我在没有 &
的情况下尝试过,但它也没有用。这是我的代码:
//My Struct
typedef struct{
int a;
double d;
char nome[20];
}contas;
//Function to allocate memory
void alloca_vetor(contas *acc, int linhas){
acc = malloc(linhas * sizeof(contas));
if(acc == NULL){
printf("ERRO AO ALOCAR MEMORIA\n");
exit(0);
}
printf("ALLOCATION SUCCESSFUL");
}
//Function to fill the vector
void fill_vetor(contas *acc, int linhas){
int i,a;
for(i=0; i< linhas; i++){
acc[i].a = i;
}
printf("FILL SUCCESSFUL !\n");
for(i=0; i< linhas; i++){
printf("%i\n", acc[i].a);
}
}
int main()
{
int i, num_linhas = 5;
contas *array;
alloca_vetor(&array, num_linhas);
fill_vetor(&array, num_linhas);
// ERROR HAPPENS HERE - Segmentation Fault
for(i=0; i < num_linhas; i++){
printf("%i\n", array[0].a);
}
free(array);
return 0;
}
按以下方式重写函数alloca_vetor
void alloca_vetor( contas **acc, int linhas ){
*acc = malloc(linhas * sizeof(contas));
if(*acc == NULL){
printf("ERRO AO ALOCAR MEMORIA\n");
exit(0);
}
printf("ALLOCATION SUCCESSFUL");
}
然后像
一样调用函数fill_vetor
fill_vetor(array, num_linhas);
我无法通过 索引符号 在 主函数 中访问我的指针。我将指针作为参数传递给函数的方式对吗?我在没有 &
的情况下尝试过,但它也没有用。这是我的代码:
//My Struct
typedef struct{
int a;
double d;
char nome[20];
}contas;
//Function to allocate memory
void alloca_vetor(contas *acc, int linhas){
acc = malloc(linhas * sizeof(contas));
if(acc == NULL){
printf("ERRO AO ALOCAR MEMORIA\n");
exit(0);
}
printf("ALLOCATION SUCCESSFUL");
}
//Function to fill the vector
void fill_vetor(contas *acc, int linhas){
int i,a;
for(i=0; i< linhas; i++){
acc[i].a = i;
}
printf("FILL SUCCESSFUL !\n");
for(i=0; i< linhas; i++){
printf("%i\n", acc[i].a);
}
}
int main()
{
int i, num_linhas = 5;
contas *array;
alloca_vetor(&array, num_linhas);
fill_vetor(&array, num_linhas);
// ERROR HAPPENS HERE - Segmentation Fault
for(i=0; i < num_linhas; i++){
printf("%i\n", array[0].a);
}
free(array);
return 0;
}
按以下方式重写函数alloca_vetor
void alloca_vetor( contas **acc, int linhas ){
*acc = malloc(linhas * sizeof(contas));
if(*acc == NULL){
printf("ERRO AO ALOCAR MEMORIA\n");
exit(0);
}
printf("ALLOCATION SUCCESSFUL");
}
然后像
一样调用函数fill_vetorfill_vetor(array, num_linhas);