2013-08-06 102 views
4

假设我有这样的话:老虎,狮子,长颈鹿。如何存储并打印2d字符/字符串数组?

我怎样才能将其存储在使用for环和scanf然后二维数组char使用for循环打印字一个一个?

喜欢的东西

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

PS对不起,问这样一个基本的问题,但我找不到在谷歌一个合适的答案。

+1

如何'str'声明? –

+0

我感应到缓冲区溢出;) – spartacus

回答

8

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

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD]; 

然后,你需要在最后向oreder输入字符串到数组

int i; 
for (i=0; i<NUMBER_OF_WORDS; i++) { 
    scanf ("%s" , arrayOfWords[i]); 
} 

打印它们使用

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

这不是动态的,也不使用指针数组 – Magn3s1um

+8

他没有问那些东西。仔细阅读问题。 –

+0

完美运行@Ran Eldan –

2
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]); 
} 
2

你可以做到这样。

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

2)动态分配内存。

3)通过scanf获取数据。一个简单的实现低于

#include<stdio.h> 
#include<malloc.h> 

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]);  
    } 
} 
1
#include<stdio.h> 
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 ; 
} 
+0

如果你解释了你的代码的确切含​​义,它可能会更有用。 – Nae