我尝试使用指针在结构中创建二维数组,因为我是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调整为所需的大小,但是无论如何,存储大小都是固定的。

10-04 16:27
查看更多