问题描述
如果我有一个函数
int * retArray()
{
int a [3] = {102,222,355};
printf("%p",a);
返回a;
}
然后在main()
int * p = retArray();
p ++;
printf(" \ n%p \ n%d",p,* p);
编译器警告我:../ c_test.c:在函数''retArray'':
... / c_test.c:24:警告:函数返回局部变量的地址
,为什么数组变量值仍然存在?
我已经研究过当函数结束局部变量失去时
他们的价值因为他们被摧毁了所以如果我想要他们没有被摧毁我应该使用
他们面前的静态字......
Hi,
in a function if I have
int * retArray()
{
int a[3] = {102,222,355};
printf("%p ", a);
return a;
}
and then in main()
int *p = retArray();
p++;
printf(" \n%p\n %d", p, *p);
the compiler warning me: ../c_test.c: In function ''retArray'':
.../c_test.c:24: warning: function returns address of local variable
and for this why the array variables values are still there ?
I''ve studied that when the function end the local variables loosing
their values as they
are distroyed and so If I want that they are not destroyed I should use
the static word before them...
推荐答案
尝试访问该指针是未定义的行为,这意味着
事情可以工作,不工作,工作一段时间时间等等。
It is undefined behavior to try to access that pointer, meaning
things could "work",not work, work for a period of time, etc.
您将返回指向数组本地元素的指针。
此数组具有自动存储功能,当函数
结束时,它超出范围。
你可以让调用者传入一个指向存储的指针,你的
函数可以摆弄它。
You are returning a pointer to a local element of your array.
This array has auto storage, it goes out of scope when the function
ends.
You could have the caller pass in a pointer to storage where your
function can fiddle with.
不要使用静态。
#include< stdio.h>
#include< stdlib.h>
void doArray(int * a,size_t c)
{
size_t i;
for(i = 0; i< c; i ++)printf("%p ",(void *)& a [i]);
printf(" \ n");
return;
}
int main(无效)
{
int a [3] = {102,222 ,355};
doArray(a,3);
返回0;
}}
Don''t use static.
#include <stdio.h>
#include <stdlib.h>
void doArray(int *a, size_t c)
{
size_t i;
for (i = 0; i < c; i++) printf("%p ", (void *)&a[i]);
printf("\n");
return;
}
int main(void)
{
int a[3] = { 102, 222, 355 };
doArray(a, 3);
return 0;
}}
是的但我的问题是相对于数组创建的情况
在一个函数内:)
yes but my question was relative to the situation of an array creation
inside a funcion :)
这篇关于为什么价值仍然可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!