简体   繁体   English

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

[英]Two dimensional array of string in struct-C

I am trying to make a two dimensional array in a struct using pointer since I am new to c and get quite confuse in the topic of pointer.我正在尝试使用指针在结构中创建一个二维数组,因为我是 c 的新手并且对指针的主题感到非常困惑。 Help please!请帮忙!

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;
}

You've declared coursecode to be a pointer to char , but you need to allocate space for it, which you can do with malloc .您已将coursecode声明为指向char的指针,但您需要为其分配空间,这可以使用malloc

And you've declared coursesession to be an array of 5 pointers to char .并且您已将coursesession声明为指向char的 5 个指针的数组。 You need to allocate space for all 5 pointers, again with malloc .您需要为所有 5 个指针分配空间,再次使用malloc

Alternatively, you could declare both of them as arrays, eg或者,您可以将它们都声明为数组,例如

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

This declares coursecode to be an array of 100 char , and coursesession to be an array of 5 arrays of 100 char .这声明coursecode为100的阵列char ,和coursesession为100的5个数组的数组char Obviously you could adjust the 100 to whatever you need, but the storage size would be fixed regardless.显然,您可以将100调整为您需要的任何值,但无论如何存储大小都是固定的。

You can modify code like this您可以像这样修改代码

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


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

int main()
{

    int n,i = 0;
    int numSession = 0;
    struct course main;

    main.coursecode = (char *)malloc(100*sizeof(char));
    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 (i = 0; i < numSession; ++i)
    {
        printf("Enter the session code (M1...):"); 
        main.coursesession[i] = (char *)malloc(100*sizeof(char));
        scanf("%s", main.coursesession[i]);
    }
    ++n;
    free(main.coursecode);
    for (i = 0; i < numSession; ++i){
        free(main.coursesession[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM