2D指针数组到2d数组

时间:2014-06-18 06:23:52

标签: c arrays string

如何转换

char *s[]={
           "to err is human",
           "but to really mess things up ",
           "one needs to know c!!"
           };  

char s[3][50]={
           "to err is human",
           "but to really mess things up ",
           "one needs to know c!!"
           };

3 个答案:

答案 0 :(得分:1)

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

int main(void){
    char *s[]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
    };
    int i, size = sizeof(s)/sizeof(*s);
    char ns[size][50];//or use malloc, E.g next line
    //char (*ns)[50] = calloc(size, sizeof(char[50]));
    for(i=0;i<size;++i){
        memset(ns[i], 0, 50);//unnecessary if you use the calloc
        strcpy(ns[i], s[i]);
        //printf("%s\n", ns[i]);
    }
/*
    char ns[3][50]= {
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
    };
*/
    return 0;
}

答案 1 :(得分:0)

确实已经是,只需删除[]的[3]下标:

#include <stdio.h>

int main (void) {

    char s[][50]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!"
        };

    int i = 0;

    for (i = 0; i < 3; i++)
        printf ("s [%d]  %s\n", i, s[i]);

    return 0;

}

输出:

s [0]  to err is human
s [1]  but to really mess things up
s [2]  one needs to know c!!

您原来的char *s[]={也可以使用。

答案 2 :(得分:-1)

无需记住数组的大小

#include <stdio.h>
#include <string.h>

int main (void) {

char *s[]={
        "to err is human",
        "but to really mess things up ",
        "one needs to know c!!",
        '\0'
        };
    int i = 0;
    char SA[100][100];
    while (s[i]  != '\0') {
        strcpy(SA[i],s[i]);
        i++;
        }
                    SA[i]='\0'
    printf("SA[1][1] : %c\n",SA[1][1])  ;
    return 0;

}

输出

 SA[1][1] : u (as expected)