我在main中声明了一个结构数组,并将其作为参数传递给称为“ change”的函数。在函数“ change”中,我尝试初始化数组,但出现en错误。
/* main.c file */
#include "header.h"
int main(int argc, char *argv[]) {
Word arr[MAX_ARRAY];
change(&arr);
return 0;
}
/* header.h file*/
#ifndef UNTITLED_HEADER_H
#define UNTITLED_HEADER_H
#include <stdio.h>
#define MAX_ARRAY 1000
typedef struct Word *Word;
enum WordTag {FIRST_WORD, INFO_WORD1, INFO_WORD2};
void change(Word *arr);
#endif
/* functions.c */
#include "header.h"
#include "data.h"
void change(Word *arr) {
struct Word *word;
word->tag = INFO_WORD2;
word->type.info2.are = 4;
word->type.info2.dest = 1;
word->type.info2.source = 1;
arr[5] = word;
}
/* data.h */
#ifndef UNTITLED_DATA_H
#define UNTITLED_DATA_H
#include "header.h"
struct FirstWord {
unsigned int are : 3;
unsigned int destOperand : 4;
unsigned int sourceOperand : 4;
unsigned int opcode : 4;
};
struct InfoWord1 {
unsigned int are : 3;
unsigned int op : 12;
};
struct InfoWord2 {
unsigned int are : 3;
unsigned int dest : 3;
unsigned int source : 3;
};
struct Word {
enum WordTag tag;
union {
struct FirstWord first;
struct InfoWord1 info1;
struct InfoWord2 info2;
} type;
};
#endif
当我尝试运行它时,出现以下错误:
word->tag = INFO_WORD2;
出现在文件功能中。c。
我将提到我需要对其进行编译,而不会收到带有标志的任何警告:
gcc -Wall -ansi -pedantic main.c functions.c
另外,我会提到,这只是我真实代码的一个示例。因此,这里我仅更改arr [5](作为示例),但是我真的不知道我需要预先在函数“ change”内部初始化哪个索引。因此,我发送了完整的数组,并且不能作为参数来“更改”指向需要初始化的结构的特定指针。
正如@gerwin指出的那样,您在中使用了未初始化的指针change()
。
这是您可以解决的一个更改(总是有很多方法可以给猫皮:)):
void change(Word *arr) {
struct Word *word = (struct Word*)malloc( sizeof( struct Word ) );
word->tag = INFO_WORD2;
word->type.info2.are = 4;
word->type.info2.dest = 1;
word->type.info2.source = 1;
arr[0] = *word;
free( word );
}
但是,您实际上甚至不需要堆变量。更简单:
void change(Word *arr) {
struct Word word;
word.tag = INFO_WORD2;
word.type.info2.are = 4;
word.type.info2.dest = 1;
word.type.info2.source = 1;
arr[0] = word;
}
这是做您当前正在做的事情的更直接的方法:
void change(Word *arr) {
arr->tag = INFO_WORD2;
arr->type.info2.are = 4;
arr->type.info2.dest = 1;
arr->type.info2.source = 1;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句