簡體   English   中英

使用2d數組在C中存儲字符串

[英]Using 2d arrays to store strings in C

我想以下列方式創建一個處理2d數組中字符串的程序:

每行僅代表一個名稱,而列包含每個名稱的單獨字符。

像這樣:

  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)函數讀取字符串時,即使我使用了1D數組,它應該作為指向2D數組的指針並存儲每個字符串,如上所示,對吧?

以下代碼應該要求三個名稱然后打印所有,但它只打印姓氏和一些亂碼,我做錯了什么?

#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

問題出在這里:

readstring(name);

將其更改為:

readstring(name[i]);

問題是name是一個二維數組,或一個字符串數組。 因此,要訪問字符串數組中的一個字符串,您需要為該特定字符串使用索引。

實際上,調用函數readstring()需要一個字符串作為參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM