C语言 如何存储然后打印二维字符/字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18083984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:04:43  来源:igfitidea点击:

how to store and then print a 2d character/string array?

carraysstringcharacter

提问by guitar_geek

Suppose I have the words: tiger, lion, giraffe.

假设我有这些词:老虎、狮子、长颈鹿。

How can I store it in a two dimensional chararray using forloop and scanfand then print the words one by one using a forloop?

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

Something like

就像是

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

PS Sorry for asking such a basic question, but I couldn't find a suitable answer on Google.

PS 很抱歉问这么基本的问题,但我在谷歌上找不到合适的答案。

回答by Ran Eldan

First you need to create an array of strings.

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

char arrayOfWords[NUMBER_OF_WORDS][MAX_SIZE_OF_WORD];

Then, you need to enter the string into the array

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

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

Finally in oreder to print them use

最后为了打印它们使用

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

回答by Magn3s1um

char * str[NumberOfWords];

str[0] = malloc(sizeof(char) * lengthOfWord + 1); //Add 1 for null byte;
memcpy(str[0], "myliteral
#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]);    
    }
}
"); //Initialize more; for(int i = 0; i < NumberOfWords; i++){ scanf("%s", str[i]); }

回答by Santhosh Pai

You can do this way.

你可以这样做。

1)Create an array of character pointers.

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

2)Allocate the memory dynamically.

2)动态分配内存。

3)Get the data through scanf. A simple implementation is below

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

#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 ;
}

回答by slothfulwave612

##代码##