C语言 动态创建二维字符串数组



我是C的新手,同时在一个问题上工作,我正在努力动态地创建一个字符串值的二维数组,我可以访问的东西[i][j]。到目前为止,我可以创建一个字符串的一维数组,并访问它的东西[I],但我对如何做到这一点,为一个2d数组的行和列需要决定一个变量称为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]);
}

这是我目前所拥有的但是对于2d数组我不能这样做

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

你可以分配一个像

这样的二维数组
#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 );

最新更新