在C中分配浮点指针
我目前拥有的是一个简单的函数,它基本上只是在给定参数指针的情况下重新分配指针但是我收到一个错误,说我正在使用其中一个未初始化的变量。 这就是我所拥有的,错误是在线上投掷* x = * k;
float * program(const int *k) { float *x; *x = *k; return x; }
这必须是一个非常简单的修复,但我觉得我只是错过了它。
这是您的代码正在做的事情:
float * program(const int *k) { // declare a pointer to a float, but don't initialize it, // so it is not actually pointing anywhere specific yet. float *x; // Put the value pointed at by k into the location pointed at by x // But wait - we don't know where x is pointing, so this is BAD! *x = *k; return x; }
这就是你的编译器抱怨的原因。
看起来好像你正在对一个函数进行强制转换,或者通过函数实现强制转换。
编译器是正确的, x
未初始化,因此分配给*x
会导致未定义的行为(以及编译器警告您正在获取)。 这段代码可能是你想要的:
const float *program(const int *k) { const float *x = (float *)k; return x; }
你需要演员阵容 – 除非你正在以方式,方式进行编译,否则会禁用太多警告。 请注意,这仍然给你未定义的行为,但它是一种有点不同的未定义行为forms – 对于大多数系统,此代码将重新解释int
指针作为float
指针,你会得到或多或少的理智结果。 使用未初始化的变量,您根本无法分辨将会发生什么; 取消引用未初始化的指针要糟糕得多。
请记住:
A pointer is a variable that contains memory address. Other words, content of a pointer is memory address. To utilize the address, you have to request the system reserve it for you via malloc, calloc...
现在让我们检查一下你的代码:
– 第三行: float *x;
– >你声明一个指向内存地址的指针x
,它将用于存储(某些)浮点数。 但是,地址尚未分配,因此它将位于系统内存中的任何位置,当然不会仅为您保留。
– 第四行: *x = *k;
– >您访问尚未分配的内存分配 – >运行错误。 如果幸运的话(没有程序访问此内存),您可以获得k
值。
你应该在这里做的是通过调用malloc
, calloc
,…为x
分配一个内存。
如果k
指向只有1个int数,则代码应为:
float *program(const int *k) { float *x; x = (float *)malloc(sizeof(float)); *x = *k; return x; }
如果k
指向int数字的arry,请尝试自己弄清楚:)