On Mon, 19 Feb 2007 05:41:09 -0500, Martin Ambuhl
<> wrote:
>venu reddy wrote:
>> Hi all,
>> I wrote an example code like this. I am getting error as " conversion
>> to non-scalar type requested error". help me!!.
>>
>>
>> #include<string.h>
>> typedef struct
>> {
>> int val;
>> char data[10];
>> }xyz;
>>
>> main()
>> {
>>
>> xyz a={10,"abcdefg"};
>> int i=0;
>> char data[20]={0};//={1,2,5,'c'};
>> void *ptr=data;
>> ptr=memcpy(data,&a,sizeof(xyz));
>>
>> printf("%s ptr=%u data= %u \n",data,ptr,data);
>> printf("val=%u data=%s\n",((xyz)data).val,(xyz)data.data);
>> printf("val=%u data=%s\n",(xyz*)ptr->val,(xyz*)ptr->data);
>>
>> }
>> for the above progrmme i am getting errors like this (compiled in gcc)
>
>You should get even more diagnostics from gcc. You have your diagnostic
>level set far too low. You have no reason at all to think you can cast
>a char array to a struct. If you *must* play with type punning, almost
>always a bad idea, here is a better form of your code:
>
>#include <stdio.h>
>#include <string.h>
>
>typedef struct
>{
> int val;
> char data[10];
>} xyz;
>
>int main(void)
>{
> xyz a = { 10, "abcdefg" };
> char data[sizeof a];
But there is no guarantee that data is properly aligned to hold an
object of type xyz.
> void *ptr = data;
> ptr = memcpy(data, &a, sizeof a);
>
> printf("%s ptr=%p data= %p\n", data, (void *) ptr, (void *) data);
> printf("val=%u data=%s\n", (*(xyz *) data).val,
> (*(xyz *) data).data);
If data is not properly aligned, this invokes undefined behavior.
Furthermore, val is a signed int but %u expects an unsigned int.
> printf("val=%u data=%s\n", ((xyz *) ptr)->val,
> ((xyz *) ptr)->data);
> return 0;
>}
Remove del for email
|