簡體   English   中英

結構指針和該結構內部的指針

[英]pointer of struct and pointer inside that struct

我有一個問題,其中有一個結構將保存姓名、年齡和學生 ID。 我必須從用戶那里獲取輸入並在不使用任何數組表示法的情況下生成該數量的結構。 然后每個結構的參數都應該從用戶那里獲取輸入並同時打印出來。 這就像創建一個學生數據庫。 結構是:

typedef struct
{
char *name;
char *std_id;
int age;
} student;

所以我的輸入是這樣的:

Number of students: 3
Name of the student1: Bro
std_id of the student1: 46845
age of the student1: 18

Name of the student2: kim
std_id of the student2: 46867
age of the student2: 19

Name of the student3: Sean
std_id of the student3: 46862
age of the student3: 18

而 output 就像:

Name of the student1 is: Bro
std_id of the student1 is: 46845
age of the student1 is: 18

Name of the student2 is: kim
std_id of the student2 is: 46867
age of the student2 is: 19

Name of the student3 is: Sean
std_id of the student3 is: 46862
age of the student3 is: 18

主要問題是我們不能在這個問題中使用任何數組。

我嘗試通過搜索 inte.net 對問題進行編碼是這段代碼:

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


typedef struct
{
    char *name;
    char *std_id;
    int age;
} students;


int main()
{

    int num;
    printf("Type the number of students:");
    scanf("%d", &num);

    students* ptr = malloc(num * sizeof(*ptr));
    if(ptr == NULL)
    {
        printf("memory not free!");
        return 0;
    }


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

        printf("\nGive the name of the std %d:", i+1);
        (ptr+i)->name = malloc(sizeof(char)*20);
        if((ptr+i)->name == NULL)
        {
            printf("memory not free!");
            return 0;
        }
        scanf("%s", (ptr+i)->name);

        printf("Give the std_id of the std %d:", i+1);
        (ptr+i)->std_id = malloc(sizeof(char)*10);
        if((ptr+i)->std_id == NULL)
        {
            printf("memory not free!");
            return 0;
        }
        scanf("%s", (ptr+i)->std_id);

        printf("Give the age of std %d:", i+1);
        scanf("%d", (ptr+i)->age);


    }

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

        printf("\nThe name of the std %d: %s", i+1, (ptr+i)->name);
        printf("\nThe std_id of the std %d: %s", i+1, (ptr+i)->std_id);
        printf("\nThe age of the std %d: %d", i+1, (ptr+i)->age);
    }


    return 0;
}

使用此代碼,這就是我的控制台的樣子:

Type the number of students:3

Give the name of the std 1:Sean
Give the std_id of the std 1:45
Give the age of std 1:23

Process returned -1073741819 (0xC0000005)   execution time : 23.131 s
Press any key to continue.

在這里,我試圖首先運行name變量的代碼。 如果運行正確,我將實現其他變量,如name變量。 但是當我運行這段代碼時,程序只接受一個輸入就退出了。 我只是無法自己解決問題。 任何有關如何解決此問題的幫助將不勝感激。

students* ptr = malloc((sizeof(int) + sizeof(char) * 50) * num);

這根本沒有任何意義,我什至不明白你想做什么。 如果你想分配一個結構數組,那么你必須這樣做:

students* ptr = malloc(num * sizeof(*ptr));

或同等學歷:

students* ptr = malloc( sizeof(students[num]) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM