如何将char *转换为char数组或结构变量? [英] How do I convert char * to char array or structure variable?

查看:449
本文介绍了如何将char *转换为char数组或结构变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的VC ++代码中,



我想将值移到另一个变量,如:



char * buf =12345;



char logbuffer [1024];



strcpy(logbuffer ,buf);



struct xx {

int a;

char b [1024];

}



xx yy;

memcpy(& yy.b,logbuffer,strlen(logbuffer));



我想这是对的。







如果logbuffer和yy是这样的数组;



char logbuffer [2] [1024];



xx yy [2];



如果我尝试将buf的值移动到这样的变量:



strcpy(logbuffer [1],buf)和,或



memcpy(& yy [1] .b,logbuffer [1],strlen(logbuffer [1]));



编译错误说暧昧的句子....



我不知道这是什么主要问题。



请让我知道答案和正确方法。



提前谢谢。



我尝试了什么:



这个问题多浪费了1天。

解决方案

不要使用memcpy。

要将一个字符串复制到另一个字符串,请使用strcpy()。

strcpy接收到指向每个字符数组的指针,或者特定于NULL终止数组中的第一个字符。


试试这个:

  char  * buf =   12345 ; 
char logbuffer [ 1024 ];

struct xx {
int a;
char b [ 1024 ];
};
xx yy;

strcpy(logbuffer,buf);
memcpy(yy.b,logbuffer,strlen(logbuffer)); // 不要使用& on yy

char logbufferb [ 2 ] [ 1024 ];
xx yyb [ 2 ];

strcpy(& logbufferb [ 1 ] [ 0 ],buf) ; // 使用& on logbufferb [1]

memcpy(yyb [ 1 ]。b,& logbufferb [ 1 ] [ 0 ],strlen(& logbufferb [ 1 ] [ 0 ])); // 参见上述评论



请注意以上关于地址运算符(& )的注释。另请注意,使用 memcpy 不会终止字符串,因此您可能遇到问题,请始终使用 strcpy


In my VC++ code,

I want to move value to another variables like as:

char* buf ="12345";

char logbuffer[1024];

strcpy(logbuffer, buf);

struct xx{
int a;
char b[1024];
}

xx yy;
memcpy(&yy.b, logbuffer, strlen(logbuffer));

I guess this is right.

but

if the logbuffer and yy are array like this;

char logbuffer[2][1024];

xx yy[2];

and if I try to move the value of buf to those variables like this:

strcpy(logbuffer[1], buf) and, or

memcpy(&yy[1].b, logbuffer[1], strlen(logbuffer[1]));

make compile error to say ambiguous sentense....

I don't what is main problem of this.

Please let me know the answer and correct method.

Thank you in advance.

What I have tried:

1 more days wasted of this problem.

解决方案

Don't use memcpy.
To copy one string to another, use strcpy().
strcpy received a pointer to each array of characters, or to be specific, to the first character in a NULL terminated array.


Try this:

char* buf = "12345";
char logbuffer[1024];

struct xx {
    int a;
    char b[1024];
};
xx yy;

strcpy(logbuffer, buf);
memcpy(yy.b, logbuffer, strlen(logbuffer)); // do not use & on yy

char logbufferb[2][1024];
xx yyb[2];

strcpy(&logbufferb[1][0], buf);  // do use & on logbufferb[1]

memcpy(yyb[1].b, &logbufferb[1][0], strlen(&logbufferb[1][0])); // see above comments


Note the above comments with respect to the addressof operator (&). Also note that using memcpy does not null terminate the strings, so you may have problems with it, always use strcpy.


这篇关于如何将char *转换为char数组或结构变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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