【问题标题】:How to initialize dynamicly array from struct C++如何从 struct C++ 动态初始化数组
【发布时间】:2021-12-10 12:40:38
【问题描述】:

我有一个任务要编写一个函数,该函数从头文件中的结构动态初始化一个数组。并且对于某些问题,我不断收到相同的错误“使用未初始化的局部变量'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 */

这是我的代码:

#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;
}

如果有人可以帮助我,那就太好了。

【问题讨论】:

  • 你永远不会在columnData 中分配一个值main,然后你读取那个未初始化的值传递给一个函数。您可能希望拥有queue columnData 并将其作为&amp;columnData 传递给您的函数。最好是采用所有这些功能并使其成为queue 的成员。

标签: c++ struct compiler-errors initialization function-definition


【解决方案1】:

你声明了一个未初始化的指针

queue* columnData;

具有不确定的价值。所以调用函数initQueue

initQueue(columnData, size);

调用未定义的行为,因为在函数中此指针被取消引用。

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

该函数也没有设置数据成员arraySize

你需要在 main 中声明一个 queue 类型的对象

queue columnData;

然后像这样调用函数

initQueue( &columnData, size);

在函数中,您还必须设置数据成员arraySize like

columnData->arraySize = size;

注意这个调用

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

也是错误的。您正在尝试使用不正确的转换说明符 %d 输出指针。

更改上面显示的对象columnData 的声明后,printf 的调用将如下所示

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

虽然使用重载运算符会更加一致

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 2021-09-21
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多