Search code examples
cvisual-studiocompiler-errorsdynamic-memory-allocation

Visual Studio 2019 getting error C2440 with typedef data type


I'm getting that problem and don't know how to solve it:

That error:

error C2440: '=': cannot convert from 'void *' to 'node_t'

Code is:

node_t* arr = malloc(sizeof(node_t) * temp3);
    for (int i = 0; i < temp3; i++)
        arr[i] = NULL;

Thanks.


Solution

  • The type of arr[i] is node_t which is not a pointer type (I guessed this from the error message).

    This code reproduces the problem:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct
    {
      int a, b;
    } node_t;
    
    
    int main() {
      node_t* arr = malloc(sizeof(node_t) * 10);
      for (int i = 0; i < 10; i++)
        arr[i] = NULL;    
    }
    

    You probably need something like this:

    void initialize_node(node_t *node)
    {
      // adapt this to your actual node_t type
      node->a = 0;
      node->b = 0;
    }
    
    int main() {
      node_t* arr = malloc(sizeof(node_t) * 10);
      for (int i = 0; i < 10; i++)
        initialize_node(&arr[i]);
    }