【问题标题】:Using 2d arrays to store strings in C使用二维数组在 C 中存储字符串
【发布时间】:2015-07-20 23:07:36
【问题描述】:

我想制作一个程序,以下列方式处理二维数组中的字符串:

每一行仅代表一个名称,而列包含每个名称的单独字符。

像这样:

  0 1 2 3 4 5 
0 K e v i n \0
1 J o h n \0
2 L u c y \0

现在,我理解数组的方式是它们用作第一个元素的指针。因此,当我使用 readstring(name) 函数读取字符串时,即使我使用了一维数组,它也应该作为指向二维数组的指针并存储每个字符串,如上所示,对吧?

下面的代码应该要求输入三个名字然后全部打印出来,但是它只打印了姓氏和一些乱码,我做错了什么?

#include <stdio.h>
#include <stdlib.h>

void readstring(char name[]);
void get_data(char name[][15]);
void show_data(char name[][15]);

int main()
{
    char name[3][15];

    get_data(name);
    show_data(name);

    return 0;
}

void get_data(char name[][15]){
        int i=0;
        for(i=0;i<3;i++){
            printf("\nEnter name: ");
            readstring(name);
        }
}

void show_data(char name[][15]){
    int i;
    for(i=0;i<3;i++){
        printf("%s",name[i]);
    }

}

void readstring(char str[]){
    int i=0;
    while((str[i++]=getchar())!='\n' && i<15);
    str[i]='\0';

}

输出显示如下:

http://i58.tinypic.com/e7i048.jpg

【问题讨论】:

  • 注意编译器警告。他们会告诉你问题出在哪里。

标签: c arrays string pointers multidimensional-array


【解决方案1】:

问题出在这里:

readstring(name);

改成:

readstring(name[i]);

问题在于name 是一个二维数组,或者是一个字符串数组。因此,要访问字符串数组中的一个字符串,您需要为该特定字符串使用索引。

事实上,调用函数readstring() 需要一个字符串作为参数。

【讨论】:

  • 不是字符串数组”与name 不正确,get_data 不是二维数组。它是一个指向 get_data 中的 15 个 chars 数组的指针。
  • 哦!我花了一些时间来理解为什么它现在可以工作,但是谢谢!
  • @CoolGuy:谢谢!我错过了。
猜你喜欢
  • 1970-01-01
  • 2013-01-10
  • 2017-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多