从结构中打印数据

时间:2012-12-05 01:35:48

标签: c struct

我有一个嵌套的结构数组,如下所示:

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

typedef struct
{
    char* e_name;
    char* e_lastname;
}emp_name;

typedef struct
{
   emp_name name;
   int id;
}emp;

int main(int argc, char *argv[])
{
  int i;
  int cod=100;
  emp job[3];
  for (i=0;i<3;i++)
  {

     scanf("%s",&job[i].emp.e_lastname);
     job[i].id=cod;
      cod++;
 }
     for (i=0;i<3;i++)
  {
       printf("%s",job[i].emp.e_lastname);
         printf("%d\n",job[i].id);
  }
 system("PAUSE");   
    return 0;
  }

但程序在打印部分挂起,为什么? 感谢

3 个答案:

答案 0 :(得分:1)

你有三个问题:

首先您要访问:

job[i].name.e_lastname

不是

job[i].emp.e_lastname

第二你应该:

scanf("%s",&job[i].name.e_lastname); 

而不是

scanf("%s",job[i].name.e_lastname);

您没有传递&,因为它是您传递给scanf函数的数组。

第三次问题,您应该将内存分配给char *e_lastname的{​​{1}}和char *e_name阵营。

请注意:

<强> scanf的

int scanf(const char * format,...);

  

从stdin读取数据并根据参数存储它们   格式化为附加参数指向的位置。

     

附加参数应指向已分配的对象   由其对应的格式说明符指定的类型   格式字符串。 (source

所以你想要这个:

struct emp_name

考虑使用scanf是不安全的,因为:

  

如果你使用%s和%[转换不正确,那么数量   读取的字符仅受下一个空格字符的限制   出现。这几乎意味着无效的输入可以使你的   程序崩溃,因为输入太长会溢出任何缓冲区   你提供了它。无论你的缓冲区有多长,一个用户   总能提供更长的输入。一个写得很好的程序   使用可理解的错误消息报告无效输入,而不是使用   崩溃。 (source

尽管如此,他们可以采用一些解决方法来使用scanf(检查它们here

您可以使用fgets代替scanf。 fgets允许您限制将放置在缓冲区中的数据。

答案 1 :(得分:1)

你真的需要小心指针和分配的内容。 我已经重写了你的代码,但使用了错误的解决方案。检查评论。

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

typedef struct emp_name {
    /* 
     * now there you had just char*. this decares
     * a pointer to some memory but no memory is allocated.
     * if you were going with that approach you should initialize
     * the struct and assign those values to something you malloc'ed().
     * This version suffers from fixed size and a possible buffer overflow if
     * you chose scanf to write the data in the buffer.
     */
    char e_name[512];
    char e_lastname[512];
    /*
     * try to follow conventions. your previous struct declarations
     * were anonymous. if it caught an error you wouldn't know in which
     * struct it would be.  good practices here: link1 (bottom) 
     */
} emp_name_t;

typedef struct emp {
    emp_name_t emp;
    int id;
} emp_t;

int main(int argc, char *argv[]) {
    int i;
    int cod=100;
    emp job[3];
    for (i=0;i<3;i++) {
        /*
         * check out this excelent post for a secure alternative:
         * link2 (bottom)
         */
        scanf("%s",&job[i].emp.e_lastname);
        job[i].id=cod;
        cod++;
     }
     for (i=0;i<3;i++) {
         printf("%s",job[i].emp.e_lastname);
         printf("%d\n",job[i].id);
     }
     return 0;
}    

link1:openbsd style(9)

link2:disadvantages of scanf

答案 2 :(得分:0)

我看到你有:

typedef struct
{
    char* e_name;
    char* e_lastname;
}emp_name;

typedef struct
{
   emp_name name;
   int id;
}emp;

emp job[3];

那么 .emp 在以下行中做什么?它不是任何结构的成员

job[i].emp.e_lastname