简体   繁体   English

如何从struct C++动态初始化数组

[英]How to initialize dynamicly array from struct C++

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对于某些原因,我不断收到相同的错误“未初始化的局部变量‘columnData’使用这是头文件

#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.如果有人可以帮助我,那就太好了。

You declared an uninitialized pointer你声明了一个未初始化的指针

queue* columnData;

that has an indeterminate value.具有不确定的价值。 So calling the function initQueue所以调用函数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 .此外,该函数不设置数据成员arraySize

You need in main to declare an object of the type queue您需要在 main 中声明一个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在函数中,你还必须设置数据成员arraySize

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 .您正在尝试使用不正确的转换说明符%d输出指针。

After changing the declaration of the object columnData shown above the call of printf will look like更改上面显示的对象columnData的声明后, printf的调用将如下所示

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

Though it will be more consistent to use the overloaded operator <<.尽管使用重载运算符 << 会更加一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM