【问题标题】:dynamically create a 2d array of strings动态创建一个二维字符串数组
【发布时间】:2022-11-18 00:54:51
【问题描述】:

我是 C 的新手,在处理一个问题时,我正在努力动态创建一个二维字符串值数组,我可以像 things[i][j] 一样访问它。到目前为止,我可以创建一个一维字符串数组并像 thing[i] 一样访问它,但我对如何为一个二维数组执行此操作感到困惑,该二维数组的行和列需要由一个名为 total 的变量决定。


total = 7
char* *students = malloc(sizeof(char*) * total);

for(i=0;i<5;i++){
    students[i]="kitty";
}

for(i=0;i<5;i++){
    printf("%s",students[i]);
}

这是我到目前为止所拥有的,但我不能为二维数组做。

我已经创建了一个一维字符串数组

【问题讨论】:

    标签: c multidimensional-array dynamic-memory-allocation c-strings


    【解决方案1】:

    您可以分配一个二维数组,如

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    //...
    
    char ( *students )[7] = malloc( sizeof( char[5][7] ) );
    
    for ( size_t i = 0; i < 5; i++ )
    {
        strcpy( students[i], "kitty" );
    }
    
    for ( size_t i = 0; i < 5; i++ )
    {
        puts( students[i] );
    }
    
    //...
    
    free( students );
    

    另一种方法是分配一个一维指针数组,然后指向一维字符数组,例如

    char **students = malloc( 5 * sizeof( char * ) );
    
    fir ( size_t i = 0; i < 5; i++ )
    {
        students[i] = malloc( 7 * sizeof( char ) );
    }
    
    fir ( size_t i = 0; i < 5; i++ )
    {
        strcpy( students[i], "kitty" );
    }
    
    for ( size_t i = 0; i < 5; i++ )
    {
        puts( students[i] );
    }
    
    //...
    
    for ( size_t i = 0; i < 5; i++ )
    {
        free( students[i] );
    }
    free( students );
    

    【讨论】:

    • 是否动态设置数组的大小,例如,如果程序要更改 total 的值,数组的大小也会更改
    • @arka581 在这种情况下,您需要使用标准函数 realloc 重新分配数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    • 2013-12-19
    • 1970-01-01
    • 2013-02-22
    • 2011-08-14
    • 2016-08-10
    相关资源
    最近更新 更多