-2
#include <stdio.h>

void add_element(char object[20], int price);

struct linked_list {
    char object[20];
    int price;
    struct shopping_list *next;
};

struct linked_list list = {"car", 15000, NULL};
struct linked_list *last = &list;

int main() {
    add_element("snake", 340);
    printf("%s", list.object);
    return 0;
}

void add_element(char object[20], int price) {
    struct linked_list new_element = {object, price, NULL};


}

ERROR:

warning: initialization makes integer from pointer without a cast [enabled by default]

struct linked_list new_element = {object, price, NULL};

if I pass "snake" directly to struct linked_list new_element it works, but passing object it doesn't.

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

5

You are trying to initialize an array with a pointer. This attempts to convert the pointer to a char and initialize the first element with it, hence the error1.

This fragment should look like:

struct linked_list new_element = { .price = price };
memcpy(new_element.object, object, sizeof new_element.object);

1- This ought to be an error, but seems to only produce a warning because of non-standard extensions. Both GCC and Clang accept -Wall -Wextra -Wfatal-errors -pedantic-errors as a reasonably robust flag set to catch these.

Quentin
  • 62,093
  • 7
  • 131
  • 191