有人可以告诉我为什么进入循环的第一个元素后程序会卡住吗?

问题描述 投票:-1回答:1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxlong 20  

typedef struct {
    char name[maxlong];
    char surname[maxlong];
} personne;  

//writing the code to enter persons name and surname  
//.ffffffffffffffffffffffffffffffff

personne enterPersonne() {
    personne r;

    printf("write the surname: ");   
    scanf("%s",&r.name);
    printf("write the name : ");
    scanf("%s",&r.surname);

    return r;   
} 

int main (void)
{
    int dimension,i;
    personne *pers;

    printf("enter the persons count : "); 
    scanf("%d",&dimension);

    for(i=0; i<dimension; i++)
        *(pers+i) = enterPersonne(); 

    return 0;

}
c loops structure
1个回答
1
投票

就在for中的main循环之前,您需要分配一个内存缓冲区来保存pers数组的内容。

传统的方法是:

    pers = (personne *)malloc(dimension * sizeof(personne));
    if ( pers == NULL ) {
        // add code here to handle an out-of-memory condition
    }
© www.soinside.com 2019 - 2024. All rights reserved.