2015年7月16日 星期四

[C] 二維陣列(char)




1) you can use 2D char array in this way
char name[5][100];
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) You can use array of pointers in this way
char *name[5];
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) if you compile with gcc and gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"
char *name[5];
for(i=0;i<5;i++)  
{
    printf(" Enter a name which you want to register\n");  
    scanf("%ms",&names[i]);
}

文章出處:http://stackoverflow.com/questions/17466563/two-dimensional-array-of-characters-in-c





沒有留言:

張貼留言