如何存储然后打印2d字符/字符串数组?

假设我有:老虎,狮子,长颈鹿。

如何使用for循环和scanf将其存储在二维char数组中,然后使用for循环逐个打印单词?

就像是

 for(i=0;i<W;i++) { scanf("%s",str[i][0]); //to input the string } 

PS很抱歉提出这样一个基本问题,但我在Google上找不到合适的答案。

首先,您需要创建一个字符串数组。

 char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD]; 

然后,您需要将字符串输入数组

 int i; for (i=0; i 

最后在oreder打印它们使用

 for (i=0; i 
 char * str[NumberOfWords]; str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte; memcpy(str[0], "myliteral\0"); //Initialize more; for(int i = 0; i < NumberOfWords; i++){ scanf("%s", str[i]); } 

你可以这样做。

1)创建一个字符指针数组。

2)动态分配内存。

3)通过scanf获取数据。 下面是一个简单的实现

 #include #include int main() { char *str[3]; int i; int num; for(i=0;i<3;i++) { printf("\n No of charecters in the word : "); scanf("%d",&num); str[i]=(char *)malloc((num+1)*sizeof(char)); scanf("%s",str[i]); } for(i=0;i<3;i++) //to print the same { printf("\n %s",str[i]); } } 
 #include int main() { char str[6][10] ; int i , j ; for(i = 0 ; i < 6 ; i++) { // Given the str length should be less than 10 // to also store the null terminator scanf("%s",str[i]) ; } printf("\n") ; for(i = 0 ; i < 6 ; i++) { printf("%s",str[i]) ; printf("\n") ; } return 0 ; }