c - struct-C 中字符串的二维数组

标签 c pointers struct

我正在尝试使用指针在结构中创建一个二维数组,因为我是 c 的新手,并且对指针主题感到非常困惑。请帮忙!

struct course
{
    char *coursecode;
    char *coursesession[5];
};

int main()
{

    int n = 0;
    int numSession = 0;
    struct course *main = malloc(sizeof(struct course));



    printf("Enter the course code and the session in this order:");
    scanf("%s", main->coursecode);
    printf("Enter the number of session required:");
    scanf("%d", &numSession);
    for (int i = 0; i < numSession; ++i)
        {
            printf("Enter the session code (M1...):");
            scanf("%s", main->coursesession[i]);
        }
    ++n;
}

最佳答案

您已将 coursecode 声明为指向 char 的指针,但您需要为其分配空间,这可以使用 malloc 来完成>.

并且您已将 coursesession 声明为一个由 5 个指向 char 的指针组成的数组。您需要再次使用 malloc 为所有 5 个指针分配空间。

或者,您可以将它们声明为数组,例如

struct course
{
    char coursecode[100];
    char coursesession[5][100];
};

这将 coursecode 声明为 100 个 char 的数组,将 coursesession 声明为由 5 个 100 char 的数组组成的数组。显然,您可以将 100 调整为您需要的任何值,但无论如何存储大小都将是固定的。

关于c - struct-C 中字符串的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027617/

相关文章:

xcode - 在 Swift 中使用结构时如何简洁地定义模型对象?

c - 在 makefile 的帮助下编译后权限被拒绝

c++ - 将字符指针传递给函数并动态分配内存

C++ 指针运算

c - 如何为字符指针赋予字符串值?

C++ 结构数组和相等数组之间的区别

c - GCC:两个相似循环之间的矢量化差异

c - 为什么宏在 libc 中可以滥用

在 lua 中计算字节数组/用户数据的 crc16

在结构上调用 free 会引发运行时错误