我的数组仅保存存储在C中的最后一个元素

问题描述 投票:0回答:1

我想将从输入中获得的一些信息存储到特定数组中。但是,当我尝试使用输入中的名称和姓氏执行此操作时,我似乎遇到了一个问题,即最后输入的元素会覆盖前一个元素。这可能是什么问题?在此先感谢...这里的代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct ask5  {
    char *onomata[1024],*epwnyma[1024];
    int arithmoim[1024];
    float bathmoi[1024];
};

int main(int argc, char *argv[]) {
    int x,i,tempi,l,reorder,k,j,u,y,p;
    struct ask5 *m = (struct ask5*)malloc(sizeof(struct ask5));
    char *xwrismos,input[1000][1024],*tempc,newstring[4][100],*eachstring;
    float q,tempf,avg;
    FILE * fptr;
    FILE *fexit;
    k=0;
    i=0;
    fptr=fopen("input.txt", "r");   
    while(fgets(input[i], 1024, fptr)) {
        input[i][strlen(input[i]) +1 ] = '\0';    \\im putting the input in specific arrays\\
        i++;
    }
    k=i;
    l=input[0][0] - '0';         \\first row of the input shows how many info will follow\\
    x=l;
    p=0;
    for (i=1; i<x+1; i++) {
        j=0;
        u=0;
        eachstring = input[i];
        for (y=0; y<=(strlen(eachstring)); y++) {
            if(eachstring[y]==' ' || eachstring[y]=='\0') {
                newstring[u][j]='\0';
                u++;
                j=0;
            }
            else {
                newstring[u][j]=eachstring[y];
                j++;
            }
        }
        m->onomata[p]=newstring[0];  \\here is the problem\\
        m->epwnyma[p]=newstring[1];  //and here//
        sscanf(newstring[2], "%d", &m->arithmoim[p]);
        sscanf(newstring[3], "%f", &m->bathmoi[p]);
        p=p+1;
    }
    fclose(fptr);
c arrays overwrite
1个回答
0
投票
m->onomata[p]=newstring[0];  \\here is the problem\\

确实,有问题。因为您使每个m->onomata[p]指向相同的newstring[0]。与newstring[1]相同。

您可能想要复制newstring,以便您可以在下一次迭代中重用它们。您可以使用strdup

    m->onomata[p]=strdup(newstring[0]);
    m->epwnyma[p]=strdup(newstring[1]);
© www.soinside.com 2019 - 2024. All rights reserved.