I have created a new C++ project (to be able to use the graphics.h library) then I have tried to add a C project which works perfectly in C (by the way I have saved the file with .c extension). 2 line leads to error:

q = malloc(sizeof(struct QueueRecord));

this line leads to this error "invalid conversion from `void*' to `QueueRecord* "

q->array = malloc(sizeof(int) * maxElements);

and this line leads to this error "invalid conversion from `void*' to `int*' "

So to sum up what should I do in order to make this 2 lines of code working in C++? I have already tried to add (int *) to the beginning of the codes but didn't work.

Recommended Answers

All 8 Replies

I have already tried to add (int *) to the beginning of the codes but didn't work.

Explicit conversion is what's required and should work. Show us how you did that.

Unlike C, C++ requires you to typecast the return value of functions that return void*, like malloc().

Why not use new? It's C++ whereas malloc() C.

Using new same error happens :/

and here is the code

#include <stdio.h>
#include <stdlib.h>
#include "MAZEHEADER1.h"

#define MIN_QUEUE_SIZE 5
#define FALSE 0
#define TRUE 1

struct QueueRecord
{
    int capacity;
    int front;
    int rear;
    int size;
    int *array;
};


Queue CreateQueue(int maxElements)
{
	Queue q;

	if(maxElements < MIN_QUEUE_SIZE)            		
              printf("Queue size is too small\n");
              
    q = malloc(sizeof(struct QueueRecord));      
    if (q == NULL)
             printf("Out of memory space\n");
  
    q->array = malloc(sizeof(int) * maxElements);
    if (q->array == NULL)
	       printf("Out of memory space\n");
  
    q->capacity = maxElements;
    MakeEmptyQueue(q);
    return q;
}

this code works in C perfectly however when I try to save it with .cpp extension line 26 and 30 leads to error.

we already told you how to fix that problem. Go back and read previous posts.

>>Using new same error happens :
The code you posted is the same as your original code, so you made no changes at all.

thank you for your help. The code works fine now I just added (Queue) and (int *) :

q = (Queue) malloc(sizeof(struct QueueRecord));
q->array = (int *) malloc(sizeof(int) * maxElements);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.