0

I keep getting an invalid initializer error in this line:

StackObject_t new = (StackObject_t*)malloc(sizeof(StackObject_t)); 

The StackObject_t type is defined as such:

typedef struct stackObject* pStackObject_t; typedef struct stackObject { void* obj; pStackObject_t next; } StackObject_t; 

and this is the exact error I get: Error message

5
  • Please see this discussion on why not to cast the return value of malloc() and family in C.. Commented Oct 20, 2020 at 12:48
  • 2
    You're assigning a pointer to a thing (StackObject_t *) to a thing (StackObject_t). Also, recommend not using the variable name new because this is a reserved word in C++. This is fully legal in C, but it's a good habit to avoid C++ keywords just to make life easier if/when you step up to C++ Commented Oct 20, 2020 at 12:49
  • 7
    @SteveFriedl Don't be so pessimistic. Not every C programmer has to step down to C++. Commented Oct 20, 2020 at 12:56
  • 3
    Using new as identifier is a good way to get a warning if you accidentally put it in a C++ compiler. Commented Oct 20, 2020 at 12:59
  • None the less, syntax formatting IDEs tend to not make a difference between C and C++, as we can see from this SO post. So that alone is a good reason to avoid C++ keywords. Commented Oct 20, 2020 at 13:00

2 Answers 2

4

First of all, you should not cast the result of malloc as it can hide errors and C automatically casts void* to the correct pointer type. Secondly, your issue is because you have StackObject_t as the type of the variable but malloc returns a StackObject_t*. You can fix this by changing your line to StackObject_t* new = ... so the types match up.

Sign up to request clarification or add additional context in comments.

1 Comment

malloc returns a void *, not StackObject_t*. Also, C automatically converts void * to other pointer types. It is a conversion, which is an operation that is performed. It is not a cast, which is an explicit operator in source code.
0

It doesn't work for the same reason as int* ptr; int i = ptr; doesn't work. A pointer is not a valid initializer to an int.

The clang compiler gives a better diagnostic:

warning: incompatible pointer to integer conversion initializing 'StackObject_t' with an expression of type 'StackObject_t *'; dereference with * [-Wint-conversion]

Aha, StackObject_t is not compatible with StackObject_t *. You probably meant to write:

StackObject_t* ptr = malloc(sizeof *ptr); 

Details: "Pointer from integer/integer from pointer without a cast" issues

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.