【问题标题】:Is there any problem due to dynamic memory allocation?动态内存分配有什么问题吗?
【发布时间】:2020-07-30 18:19:42
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char* name;
}Student;

int main()  {

    int n,i;

    printf("Enter the number of student: ");
    scanf("%d",&n);
    Student *ptr = (Student*) malloc(n * sizeof(Student));

    for( i = 0; i < n ;i++)  {

        printf("Enter the name of student: ");
        scanf("%s", (ptr + i)->name);


    }
    return EXIT_SUCCESS;
}

我不明白为什么这段代码不起作用,谁能帮助我?我认为问题是动态内存分配,但我无法解决。

【问题讨论】:

  • 你好,也许初始化name指针?
  • 请注意,(Student *) 只有在需要 C++ 兼容性时才需要。
  • @IronMan 但如果代码是“ char * name; scanf("%s", name);"退出代码为 0。因此(在我看来)名称的初始化没有问题。
  • char *name 创建一个指向char 的指针,命名为name,而一个指针只能存储内存地址,不能在其中存储字符串。要存储字符串,您需要一个 char 数组(足够长)。
  • 表达式(ptr + i)-&gt;name的类型是pointer to char,对吧?你认为(ptr + i)-&gt;name 指向的地方是什么?

标签: c loops struct dynamic-memory-allocation


【解决方案1】:

试试这个代码。该名称未分配内存。这就是你犯的错误。

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

typedef struct {
    char* name;
}Student;

int main()  {

    int n,i;

    printf("Enter the number of student: ");
    scanf("%d",&n);
    Student *ptr = (Student*) malloc(n * sizeof(Student));

    for( i = 0; i < n ;i++)  {

        printf("Enter the name of student: ");
        char str[1024];
        scanf("%s", str);
        (ptr + i)->name = (char*)malloc(strlen(str) + 1);
        strcpy((ptr + i)->name, str);
    }
    return EXIT_SUCCESS;
}

【讨论】:

  • 请注意,(char *)(Student *) 转换仅在需要 C++ 兼容性时才需要。
  • 尝试使用更慷慨的东西,例如1024 作为缓冲区大小。 100 字节不算什么。
  • 我只是说你的缓冲区非常小,1024 比 100 更安全。
  • 但是如果代码是" char * name; scanf("%s", name);"退出代码为 0。所以(在我看来)名称的初始化没有问题。
猜你喜欢
  • 2011-01-19
  • 2022-01-22
  • 2023-03-07
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
相关资源
最近更新 更多