1

I am getting an error while assigning a character array in my object. How can I resolve this error?

typedef struct car {
    int id;
    char *name;
    int price;
    char *colors[5];
} car;

int main()
{
    car obj;
    obj.id = 5;
    obj.name = "honda city zx";
    obj.price = 1500;
    obj.colors = {"red", "blue", "black"};   // Line 17

    return 0;
}

Error :

prtemp.c: In function ‘main’:
prtemp.c:17:18: error: expected expression before ‘{’ token
     obj.colors = {"red", "blue", "black"};
0

2 Answers 2

1

Arrays do not have the assignment operator. So this statement

obj.colors = {"red", "blue", "black"}; 

is invalid. You have to write

obj.colors[0] = "red";
obj.colors[1] = "blue";
obj.colors[2] = "black"; 
obj.colors[3] = NULL;
obj.colors[4] = NULL;

Another approach is to initialize the object whent it is created.

car obj =
{
    5, "honda city zx", price = 1500, {"red", "blue", "black" }
};

Or you can use the so-called designated initialization..

 car obj =
 {
    .id = 5, .name = "honda city zx", .price = 1500, .colors = { "red", "blue", "black" }
 };     
Sign up to request clarification or add additional context in comments.

4 Comments

is there any way to achieve the same using initializer while declaring the object?
@ikegami It should not be.
@ikegami Though I agree with you to use NULL.
I am accepting your answer , anyways all the answers here are similar and correct
1

= { ... } is an initializer; it's only allowed in a definition.

So either move the initialization to the definition

car obj = {
   .id     = 5,
   .name   = "honda city zx",
   .price  = 1500,
   .colors = { "red", "blue", "black" }
};

Or use assignment.

car obj;
obj.id = 5;
obj.name = "honda city zx";
obj.price = 1500;
obj.colors[0] = "red";
obj.colors[1] = "blue";
obj.colors[2] = "black";
obj.colors[3] = NULL;
obj.colors[4] = NULL;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.