0

I have an assignment to write a function that dynamicly initialize an array from struct that is in the header file. and for some resone I am keep getting the same error "uninitialized local variable 'columnData' used this is the header file

#ifndef QUEUE_H
#define QUEUE_H


/* a queue contains positive integer values. */
typedef struct queue
{
    int arraySize;
    int* column;
} queue;

void initQueue(queue* q, unsigned int size);
void cleanQueue(queue* q);

void enqueue(queue* q, unsigned int newValue);
int dequeue(queue* q); // return element in top of queue, or -1 if empty

#endif /* QUEUE_H */

this is my code:

#include <iostream>
#include "queue.h"

int main()
{
    queue* columnData;
    unsigned int size = 0;
    std::cout << "Please enter column size: ";
    std::cin >> size;
    initQueue(columnData, size);
    printf("%d", &columnData->column[0]);

}

void initQueue(queue* q, unsigned int size) {
    q->column = new int[size];
    q->column[0] = 5;
}

void cleanQueue(queue* q) {

}

void enqueue(queue* q, unsigned int newValue) {

}

int dequeue(queue* q) {
    return 1;
}

If someone can help me it will be great.

1
  • You never assign columnData a value in main, then you read that uninitialized value to pass to a function. You might want to have queue columnData and pass it as &columnData to your functions. Better would be to take all those functions and make them members of queue. Commented Oct 24, 2021 at 22:18

1 Answer 1

1

You declared an uninitialized pointer

queue* columnData;

that has an indeterminate value. So calling the function initQueue

initQueue(columnData, size);

invokes undefined behavior because within the function this pointer is dereferenced.

q->column = new int[size];
q->column[0] = 5;

Also the function does not set the data member arraySize.

You need in main to declare an object of the type queue

queue columnData;

and call the function like

initQueue( &columnData, size);

and within the function you have to set also the data member arraySize like

columnData->arraySize = size;

Pay attention to that this call

printf("%d", &columnData->column[0]);

is also wrong. You are trying to output a pointer using the incorrect conversion specifier %d.

After changing the declaration of the object columnData shown above the call of printf will look like

printf("%d", columnData.column[0]);

Though it will be more consistent to use the overloaded operator <<.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.