C语言中的二维字符数组 [英] Two Dimensional Array of Characters in C

查看:712
本文介绍了C语言中的二维字符数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帮助我摆脱这个问题。我在ubuntu12.04上使用GCC。当我编写此程序以从键盘n获取5个字符串时,然后在屏幕上打印这些字符串。程序已编译,但在执行过程中会从键盘上获取字符串,但仅输出最后一个字符串。我编写的程序如下:

Help me to get out of this problem. I'm using GCC on ubuntu12.04. While I write this program to get 5 strings from keyboard n then print these strings on screen. Program is compiled but during execution it takes strings from keyboard but print only last string. The program which I have written is below:

void main()    
{  
    char names[10];  
    int i,j;

    for(i=0;i<5;i++)  
    {  
        printf(" Enter a name which you want to register\n");  
        scanf("%s",names);  
    }  
    for(i=0;i<5;i++)    
        printf(" the names you enter are %s\n", names);  

}


推荐答案

1)您可以通过这种方式使用2D字符数组

1) you can use 2D char array in this way

char names[5][100];

二维数组中的每一行都是大小为100的char数组

each line in the 2D array is an array of char with size = 100

for(i=0;i<5;i++)  
{
    printf(" Enter a name which you want to register\n");  
    scanf("%99s",names[i]);
}

2)您可以通过这种方式使用指针数组

2) You can use array of pointers in this way

char *names[5];

数组中的每个元素都是指向字符串(char数组)的指针。您必须在调用 scanf()

each element in the array is a pointer to a string (char array). you have to assign each pointer in the array to a memory space before you call scanf()

for(i=0;i<5;i++)  
{
    names[i]=malloc(100);  
    printf(" Enter a name which you want to register\n");  
    scanf("%99s",names[i]);
}

3)如果使用gcc版本> 2.7进行编译,则您的 scanf()可以使用%ms 代替%s

3) if you compile with gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"

char *names[5];
for(i=0;i<5;i++)  
{
    printf(" Enter a name which you want to register\n");  
    scanf("%ms",&names[i]);
}

这篇关于C语言中的二维字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆