![](/img/trans.png)
[英]C - Creating a dynamic array of structs, struct members printing wrong values?
[英]C values of dynamic array wrong
基本上在这段代码中,我将内容从txt文件保存到动态数组(直到一切都很好),但是当我尝试重新分配内存并添加更多结构时,中间的某些值会出错,总是相同的。我曾经保存到动态数组
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "header.h"
int iniF(guitarra *vg,int *tamvg)
{
int ch=0, i;
FILE *g;
g = fopen("guitarras.txt", "r"); // abrir ficheiro
if(g == NULL)
{
printf("Erro ao abrir ficheiro %s", "guitarras.txt");
}
while(!feof(g)) //check how many lines the file have
{
ch = fgetc(g);
if(ch == '\n')
{
(*tamvg)++;
}
}
fseek(g, 0, SEEK_SET);
vg = malloc(*tamvg * sizeof(guitarra));
for(i=0; i<*tamvg; i++)
{
fscanf(g, ("%d %f %f %d %s"), &vg[i].id, &vg[i].pdia, &vg[i].valor, &vg[i].estado, &vg[i].nome );
}
fclose(g);
return vg;
}
然后重新分配
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
int addguit(guitarra *vg, int *tamvg)
{
int stop=0;
do
{
vg = realloc(vg, sizeof(guitarra)); //allocating one size of struct guitarra
printf("Id: ");
scanf("%d", &vg[*tamvg].id);
printf("Preco por dia: ");
scanf("%f", &vg[*tamvg].pdia);
printf("Valor: ");
scanf("%f", &vg[*tamvg].valor);
printf("Estado: ");
scanf("%d", &vg[*tamvg].estado);
printf("Nome: ");
scanf("%s", &vg[*tamvg].nome);
printf("Deseja adicionar mais guitarras ao stock? Sim[1] Nao[0]: "); //asking if wants to allocate one more
scanf("%d", &stop);
(*tamvg)++;
}
while(stop==1);
return vg;
}
值是简单的“ 1 1 1 1 a”; “ 2 2 2 2 b”,依此类推,就可以了。
这是我正在谈论的内容的打印屏幕
您对realloc的调用不会将一个结构的大小添加到数组中。 相反,它将其大小调整为单个结构的大小(请参见参考以获取realloc )。 数组其余部分的内存不再保留,可以由其他程序声明/修改。 假设tamvg指向数组的当前长度,则应具有类似于以下内容的内容:
vg = realloc(vg, sizeof(guitarra)*(*tamvg+1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.