c语言二维字符串数组输入
时间: 2024-10-16 12:21:49 浏览: 74
在C语言中,二维字符串数组可以看作是一个表格,其中每个元素都是一个字符串。当你需要从用户那里输入这样的数组时,通常会采用循环嵌套的方式。这里有一个简单的示例:
```c
#include <stdio.h>
#include <string.h>
#define ROWS 3 // 行数
#define COLS 4 // 列数
void input_2d_string_array(char **array, int rows, int cols) {
for (int i = 0; i < rows; i++) {
char *row[row_cols]; // 创建行指针数组
for (int j = 0; j < cols; j++) {
printf("请输入第 %d 行第 %d 列的字符串: ", i+1, j+1);
scanf("%s", row+j); // 输入并存储字符串
}
array[i] = row; // 将行指针存入二维数组
}
}
int main() {
char **strArray;
strArray = malloc(sizeof(char*) * ROWS); // 分配内存给二维数组
if (strArray) {
input_2d_string_array(strArray, ROWS, COLS);
// 现在你可以遍历数组并处理输入的数据
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("第%d行第%d列的字符串: %s\n", i+1, j+1, strArray[i][j]);
}
}
// 不忘记释放动态分配的内存
for (int i = 0; i < ROWS; i++) {
free(strArray[i]);
}
free(strArray);
} else {
printf("内存分配失败!\n");
}
return 0;
}
阅读全文
相关推荐


















