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);
Several issues.
First problem is that you've created an array of char
pointers, not a char
array. You want:
char string[20];
In C, an array implicitly "degrades" into a pointer to its first element, so if you pass just string
it's a char*
( string == &string[0]
)
From there ... no idea what pp
is, but strtol()
returns a long int
which you're trying to assign to a char
- 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")
Try not to cast between char*
and char
– it does not do anything useful and your compiler should not let you do that, anyway. If you really want to use strcat
, that should be
char cc; // no ="" here!
...
tt[0] = cc;
strcat(string, tt)
But it would be much easier to just do what cnicutar posted above (I was going to type something like that here, too).
精彩评论