【问题标题】:Same output shows all the time in structure.. How can I fix it?相同的输出一直显示在结构中。我该如何解决?
【发布时间】:2022-01-15 07:52:38
【问题描述】:

下面是结构示例的代码。当我一直为不同的人添加多个信息时,它显示的输出与最后插入的信息相同。我该如何解决?

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

struct Person{

       char *name;
       char *adress;

}p[100];

void insert(int ind , char *name, char *adress){

      p[ind].name = name;
      p[ind].adress = adress;
}

void display(int n){`enter code here`

   for(int i =0 ; i<n ; ++i){
     printf("%s %s\n" , p[i].name , p[i].adress);
   }
}


int main(){
char name[100] , address[100];

    for(int i = 0 ; i<2 ; ++i){

         fflush(stdin);
         gets(name);
         fflush(stdin);
         gets(address);
         insert(i , name , address);
    }


   display(2);


  return 0;
}

【问题讨论】:

  • 您永远不会复制insert 中的姓名和地址;您只需将指针元素指向两个数组。这两个数组将始终采用您输入的最后一个值,因此所有结构元素始终显示最后两个值。
  • 要进行复制,您可以使用strdupp[ind].adress = strdup(adress); 等函数。只需确保检查strdup 的返回值不是NULL
  • 为了显示所有信息我应该怎么做?
  • 您的代码还有其他问题,因为它会在名称和地址超过 100 个字符(是的,世界上存在)时失败(或导致严重问题)。我认为gets也不推荐; fgets(和stdin)会更好。

标签: c string structure


【解决方案1】:

为了存储和输出所有信息,您需要为它们提供单独的内存。
显示的代码总是覆盖相同的缓冲区并只存储指向该缓冲区的指针。
对您的结构定义稍作更改,即可确保提供内存,而不是仅存储一个指针(指向始终相同的内存)。

然后读入单独的内存,这也节省了C类型字符串的其他必要复制,这很乏味。

以下代码使用所描述的概念显示所有信息:

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

struct Person{

       char name[100];
       char adress[100];

}p[100];

void display(int n){

   for(int i =0 ; i<n ; ++i){
     printf("%s %s\n" , p[i].name , p[i].adress);
   }
}


int main(){

    for(int i = 0 ; i<2 ; ++i){

         // fflush(stdin); Not using this is a habit you should adopt.
         // gets(name); Not using this is a habit you should adopt.
         fgets(p[i].name, 99, stdin);
         // fflush(stdin); Not using this is a habit you should adopt.
         fgets(p[i].adress, 99, stdin);
    }


   display(2);


  return 0;
}

对于例如的输入:

name1
address1
name2
address2
a
b
c
d
e
f
g
h

(在预期的输入之后有意附加输入,以显示干净的结尾)

输出是你要求的,有不同的信息,而不是总是一样的。

name1
 address1

name2
 address2

您可能想要替换与输入一起读入的换行符。

【讨论】:

  • 在使用fgets() 替换gets() 时不要忘记换行。
  • @JonathanLeffler 我提到过。但回答问题时不需要它。
猜你喜欢
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 2015-11-09
  • 1970-01-01
  • 2020-09-14
  • 2020-06-27
相关资源
最近更新 更多