1

Hi i am creating a sample program like this

#include<stdio.h>
int main()
{
    typedef struct {
                int a;
                int b;
            }v;
v m;
int g =54;
m=(v)g;

}

while compiling i am getting error as conversion to non-scalar type requested. what is the problem here.

Engineer2021
  • 3,288
  • 6
  • 29
  • 51
mrigendra
  • 1,472
  • 3
  • 19
  • 33
  • 1
    How can you know how to cast and not how to access members? – this May 06 '14 at 13:36
  • possible duplicate of [Error: Conversion to non-scalar type requested](http://stackoverflow.com/questions/9561306/error-conversion-to-non-scalar-type-requested) – alk May 06 '14 at 13:36
  • 1
    The error message is right there. Do you know what a scalar type is? – Engineer2021 May 06 '14 at 13:36
  • no i don't know what scalar type is – mrigendra May 06 '14 at 13:38
  • That's the problem then.. http://ee.hawaii.edu/~tep/EE160/Book/chap5/section2.1.3.html – Engineer2021 May 06 '14 at 13:38
  • 1
    A scalar type is a type that represents a single value, that is an `int`, a `double`, even a pointer. Examples of non-scalar types are arrays and structs. Your code is trying to cast a scalar value to a non-scalar type, and that is not allowed, hence the error. – rodrigo May 06 '14 at 13:40

3 Answers3

1

v and int are not the same size and the compiler has no rule on how to convert from int to v.

The compiler has rules for conversion between scalar types (char, short, int, long, float, double).

If you want to assign a struct, you either need a struct of the same type, or you can assign the fields separately:

m.a = 54;
m.b = 32;
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
  • so in essence there is no really a user defined data type. assignments are done on typical datatypes only. – mrigendra May 06 '14 at 14:12
  • @mrigendra: You can assign a `struct` to another `struct`. You just can't cast from a scalar type to a non-scalar type. How do you expect the compiler to assign the memory in `g` to the `struct v`? – Engineer2021 May 06 '14 at 16:15
0

You are getting this error as it is unclear wether you want to assign 54 to m.a or m.b

m.a = g

or

m.b = g

is probably wat you want.

jayjay
  • 1,017
  • 1
  • 11
  • 23
  • i thought typedef will create a datatype same as typical datatype. a typical datatype does not have any members just a size , so i am just assigning 54 as 4 bytes inside m. – mrigendra May 06 '14 at 13:42
  • typedef, in this case, is just a shortcut; enabling you to use the type `v` instead of `struct v`. you are attempting to write an `int` (probably 4 bytes) onto a `v` (probably 8 bytes, made up of 2 ints), this is where your error comes from. – jayjay May 06 '14 at 13:47
0

The construct that you are using (v) is an explicit conversion or "cast". Cast are only allowed for base types (here "scalar types" in your error message), not for structure types.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177