C语言 警告:在此函数中可以使用未初始化的 X
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12958931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning: X may be used uninitialized in this function
提问by Valentino Ru
I am writing a custom "vector" struct. I do not understand why I'm getting a Warning: "one" may be used uninitializedhere.
我正在编写一个自定义的“向量”结构。我不明白为什么我会在Warning: "one" may be used uninitialized这里。
This is my vector.h file
这是我的 vector.h 文件
#ifndef VECTOR_H
#define VECTOR_H
typedef struct Vector{
int a;
int b;
int c;
}Vector;
#endif /* VECTOR_ */
The warning happens here on line one->a = 12
警告发生在这里在线 one->a = 12
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include "vector.h"
int main(void){
Vector* one;
one->a = 12;
one->b = 13;
one->c = -11;
}
回答by simonc
onehas not been assigned so points to an unpredictable location. You should either place it on the stack:
one尚未分配,因此指向不可预测的位置。您应该将它放在堆栈上:
Vector one;
one.a = 12;
one.b = 13;
one.c = -11
or dynamically allocate memory for it:
或为其动态分配内存:
Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);
Note the use of freein this case. In general, you'll need exactly one call to freefor each call made to malloc.
请注意free在这种情况下的使用。一般而言,free对于每次调用,您只需要一次调用malloc。
回答by dasblinkenlight
You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.
您收到警告是因为您没有为 赋值one,它是一个指针。这是未定义的行为。
You should declare it like this:
你应该这样声明:
Vector* one = malloc(sizeof(Vector));
or like this:
或者像这样:
Vector one;
in which case you need to replace ->operator with .like this:
在这种情况下,您需要像这样替换->运算符.:
one.a = 12;
one.b = 13;
one.c = -11;
Finally, in C99 and later you can use designated initializers:
最后,在 C99 及更高版本中,您可以使用指定的初始化程序:
Vector one = {
.a = 12
, .b = 13
, .c = -11
};
回答by plaknas
When you use Vector *oneyou are merely creating a pointer to the structure but there is no memory allocated to it.
当您使用时,Vector *one您只是在创建一个指向该结构的指针,但没有为其分配内存。
Simply use one = (Vector *)malloc(sizeof(Vector));to declare memory and instantiate it.
简单地用于one = (Vector *)malloc(sizeof(Vector));声明内存并实例化它。

