复制二维字符串数组 [英] Copying two dimentional string array

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

问题描述

您好,


我有以下二维字符串数组(two_d_arr),我想复制到另一个字符串数组(one_d_arr)。


char * two_d_arr [] [3] = {{" brown" ,黄色 ,red},

{" apple" ,橙色 ,柠檬, },

{" one" ,两个, ,$}};


char * one_d_arr;


int i;

for(i = 0; i< 3; i ++){

strncpy(one_d_arr [i],two_d_arr [1] [i],strlen(one_d_arr [i])+ 1);

}


printf("%s \ n",one_d_arr [0]);

printf("%s \ n" ;,one_d_arr [1]);

printf("%s \ n",one_d_arr [2]);


我继续获取错误:

警告:传递arg 1的`strlen''使得整数指针没有强制转换


和分段错误。

请帮忙。

解决方案

变量one_d_arr只是一个指向char的指针,因此one_d_arr [i]是一个被提升为int的char;那就是你的编译器抱怨 :它期望一个指针(对一个char)。但更重要的是:你的one_d_arr并没有指向任何东西,所以如果你把东西复制到那个位置,你就会把它复制到无处可去的地方:一个分段错误可能都属于你。


亲切的问候,


Jos


你的意思是你希望你编程转换这个输入:

展开 | 选择 | Wrap | 行号


@donbock


我想将以下元素复制到one_d_arr:

{" apple" ,橙色 ,柠檬, }


这样:


* one_d_arr = {" apple" ,橙色 ,柠檬, };

Hello,

I have the following two dimensional string array (two_d_arr) which I would like to copy on to another string array (one_d_arr).

char *two_d_arr[][3] = { {"brown" , "yellow" , "red"} ,
{"apple" , "orange" , "lemon" },
{ "one" , "two" , "three"} };

char *one_d_arr;

int i;
for(i=0;i < 3; i++){
strncpy(one_d_arr[i],two_d_arr[1][i],strlen(one_d_arr[i])+1);
}

printf("%s\n", one_d_arr[0]);
printf("%s\n", one_d_arr[1]);
printf("%s\n", one_d_arr[2]);

I keep on getting the error:
warning: passing arg 1 of `strlen'' makes pointer from integer without a cast

and segmentation fault.

Please help.

解决方案

Variable one_d_arr is just a pointer to a char so one_d_arr[ i ] is a char that gets promoted to an int; that''s what your compiler is complaining about: it expected a pointer (to a char). But more important: your one_d_arr doesn''t point to anything so if you copy something to that location you''ll copy it to nowhere and whammo: a segmentation fault can be all yours.

kind regards,

Jos


Do you mean that you want you program to convert this input:

Expand|Select|Wrap|Line Numbers


@donbock
I wanted to copy the following elements to one_d_arr:
{"apple" , "orange" , "lemon" }

so that :

*one_d_arr = {"apple" , "orange" , "lemon" };


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

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