![](/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.