Pointers 为什么fgets()不在这里工作?

Pointers 为什么fgets()不在这里工作?,pointers,structure,fgets,Pointers,Structure,Fgets,在下面的代码中,scanf()正在从用户处获取名称,但是fgets()不起作用。请有人帮助我理解为什么它不起作用 #include <stdio.h> #include <stdlib.h> typedef struct university{ int roll_no; char name[16]; }uni; int main() { uni *ptr[5],soome;char i,j=0; for(i=0;i<5;i++)

在下面的代码中,scanf()正在从用户处获取名称,但是fgets()不起作用。请有人帮助我理解为什么它不起作用

#include <stdio.h>
#include <stdlib.h>
typedef struct university{
    int roll_no;
    char name[16];
}uni;
int main()
{
    uni *ptr[5],soome;char i,j=0;
    for(i=0;i<5;i++)
    {
        ptr[i]=(uni*)calloc(1,20);
        if(ptr[i]==NULL)
        {
            printf("memory allocation failure");
        }
        printf("enter the roll no and name \n");
        printf("ur going to enter at the address%u \n",ptr[i]);
        scanf("%d",&ptr[i]->roll_no);
        //scanf("%s",&ptr[i]->name);
        fgets(&ptr[i]->name,16,stdin);
    }
    while(*(ptr+j))
    {
        printf("%d %s\n",ptr[j]->roll_no,ptr[j]->name);
        j++;
    }
    return 0;
}
#包括
#包括
typedef struct大学{
国际卷号;
字符名[16];
}大学;
int main()
{
uni*ptr[5],soome;char i,j=0;
对于(i=0;iroll_no);
//scanf(“%s”,&ptr[i]->名称);
fgets(&ptr[i]->名称,16,标准输入法);
}
而(*(ptr+j))
{
printf(“%d%s\n”,ptr[j]->卷号,ptr[j]->名称);
j++;
}
返回0;
}
首先,
fgets(char*s,int n,FILE*stream)
接受三个参数:指向字符数组开头的指针、计数n和输入流。
在原始应用程序中,您使用地址运算符
&
获取的指针不是指向
名称[16]
数组的第一个元素,而是指向其他元素(要使用地址运算符,您应该引用数组中的第一个字符:
名称[0]

您在应用程序中使用了很多幻数(例如,20作为
uni
struct的大小)。在我的示例中,我尽可能多地使用sizeof。
考虑到您使用的是
calloc
,我使用了这样一个事实,即第一个参数是大小等于第二个参数的元素数,以便一次预先分配所有五个uni结构

最终结果是:

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

#define NUM_ITEMS (5)
#define NAME_LENGTH (16)

typedef struct university{
  int roll_no;
  char name[NAME_LENGTH];
} uni;

int main()
{
  uni *ptr;
  int i;

  ptr = (uni*)calloc(NUM_ITEMS, sizeof(uni));
  if(NULL == ptr) {
    printf("memory allocation failure");
    return -1;
  }

  for(i=0; i<NUM_ITEMS; i++) {
    printf("enter the roll no and name \n");
    printf("You're going to enter at the address: 0x%X \n",(unsigned int)&ptr[i]);
    scanf("%d",&ptr[i].roll_no);
    fgets(ptr[i].name, NAME_LENGTH, stdin);
  }
  for(i=0; i<NUM_ITEMS; i++) {
    printf("%d - %s",ptr[i].roll_no,ptr[i].name);
  }

  free(ptr);
  return 0;
}
#包括
#包括
#定义NUM_项(5)
#定义名称和长度(16)
typedef struct大学{
国际卷号;
字符名称[名称长度];
}大学;
int main()
{
uni*ptr;
int i;
ptr=(uni*)calloc(NUM_项,sizeof(uni));
if(NULL==ptr){
printf(“内存分配失败”);
返回-1;
}

对于(i=0;i)您得到的错误是什么?