Desperately need C help

Bluga

Banned
Nov 28, 2000
4,315
0
0
This string copy works:

strcpy((char *)task->data, "a" );


But why doesn't this work??

i=1;
strcpy((char *)task->data, i );


**note task is a structure and data is pointer to void.
 

stndn

Golden Member
Mar 10, 2001
1,886
0
0
strcpy only copies one string to another
in your first case, it works because "a" (with the double quote) is a string
in the second case, it doesn't work because i (or 1) is an integer (or so i assume, based on the value you assigned to the variable i)

however, if you use
strcpy ((char*)task->data, "1");
i'm sure it will work...

-1036-
 

RSMemphis

Golden Member
Oct 6, 2001
1,521
0
0
Well, there is also a trick you can use.

First of all, do you want it to contain a binary one, or the character one (those are two different things!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!)

If you want a binary one, it's easy.
If you want a character one, you have to add 0x030 (hex 30 = the character "0") or 48

and then you can use a trick. A string is anything NULL terminated. Any integer (they ARE at least 16 bit) are NULL terminated if smaller than 256.
But you again need a pointer (a string variable is always a pointer)...

you could do
i=1;
strcpy((char *)task->data, &i );

or

i=1;
i+=0x30; // alternatively i+=48;
strcpy((char *)task->data, &i);

It's kinda ugly, but it will work.

Edit: fixed the fact that ; ) will be made a ;) when written together.
 

RSMemphis

Golden Member
Oct 6, 2001
1,521
0
0
The reason why you get the segmentation fault, btw

It interprets i as a pointer (you probably got a warning that the compiler recast i.... Don't ignore warnings)

Since i=1, you address some very early memory, where mostly OS stuff resides... OS no likee...
 

Argo

Lifer
Apr 8, 2000
10,045
0
0
If you want to copy '1' as a string you can use sprintf function.

int i = 10;

sprintf(task->data, "The value of i is: %d", i);


Upon completion task->data will contain: "The value of i is: 10"