将字符复制到字符*
我有一个关于 C 编程的问题。 我有一个循环,在每次迭代时生成一个新字符。我想将每个生成的字符附加到字符串(char *) 这是我的代码:
char *string[20];
string[0]=0;
for (p = 0; p < length(message) - 1; p = p + 2)
{
...
char cc="";
cc = (char) strtol(pp, pp, 16);
char *tt[2];
tt[0]="";
*tt=(char *)cc;
strcat(string,cc);
}
我知道 strcat 使用 char*。所以我尝试复制我想要附加到新指针的字符的内容。 我可能做错了……我经验不足。 谢谢
strtol 的原因: 我有一个 char* 消息,其中包含一个十六进制数字。我想处理该十六进制数,但是当我尝试执行例如移位 (<<16) 时,会将十六进制字符的十进制 ascii 值移位 16 位(乘以 2^16 ),而不是移位字符本身。 因此,我将十六进制数字转换为字符,这样当我尝试进行移位时,它将移位正确的值。我知道这很奇怪。 你能帮我想出更好的办法吗?
unsigned char *octets0"3F214365876616AB15387D5D59";
crc ^= ((*octets++) << 16);
I have a question for C programming.
I have a loop where I generate at each iteration a new char. Each generated char I want to append to a string (char *)
This is my code:
char *string[20];
string[0]=0;
for (p = 0; p < length(message) - 1; p = p + 2)
{
...
char cc="";
cc = (char) strtol(pp, pp, 16);
char *tt[2];
tt[0]="";
*tt=(char *)cc;
strcat(string,cc);
}
I know that strcat uses char*. So I tried to copy the content of the char i wanna append to a new pointer.
I have probably done sth wrong...i'm not very experienced.
Thank you
Reason for strtol:
I have a char* msg, that holds a hexa number. I want to process that hexa number but when I try to do for instance shifting (<<16) is shifts 16 bits (multiplies by 2^16 ) the decimal ascii value of the hexa character, instead of shifting the character itself.
So, I converted the hexa number to a character, so that when I try to do shifting it will shift the correct value. I know it' wierd.
Cann you help me come up with sth better?
unsigned char *octets0"3F214365876616AB15387D5D59";
crc ^= ((*octets++) << 16);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
几个问题。
第一个问题是您创建了一个
char
指针数组,而不是一个char
数组。您想要:在 C 中,数组隐式“降级”为指向其第一个元素的指针,因此如果您仅传递
string
它就是一个char*
(string = = &string[0]
)从那里...不知道
pp
是什么,但是strtol()
返回一个long int 您试图分配给
char
- 这不会像你想象的那样工作。你少了大约7个字节。(编辑为“工作”定义为“不是你所想的”)
Several issues.
First problem is that you've created an array of
char
pointers, not achar
array. You want:In C, an array implicitly "degrades" into a pointer to its first element, so if you pass just
string
it's achar*
(string == &string[0]
)From there ... no idea what
pp
is, butstrtol()
returns along int
which you're trying to assign to achar
- that's not going to work the way you think. You're short about 7 bytes.(Edited to define "work" as in "Not what you think")
尽量不要在
char*
和char
之间进行转换——它不会做任何有用的事情,而且你的编译器无论如何也不应该让你这样做。如果你真的想使用 strcat,那应该是但是按照 cnicutar 上面发布的内容会容易得多(我也打算在这里输入类似的内容)。
Try not to cast between
char*
andchar
– it does not do anything useful and your compiler should not let you do that, anyway. If you really want to usestrcat
, that should beBut it would be much easier to just do what cnicutar posted above (I was going to type something like that here, too).