2015-06-20 70 views
-2

我的C函数代码不断给我错误,我不知道什么是错的。C代码奇怪(指针)

int * myfunc(int a) 
{ 
    int * newNum, i; 
    i = a*a; 
    *newNum = i; 
    return newNum; 
} 
+0

'newNum'需要的地方点...... – Diego

+0

这篇文章可能会帮助你:http://stackoverflow.com/questions/1224042/returning-a-pointer-to-an-automatic-variable –

+0

返回悬挂指针;-)自动变量我在myfunc返回后超出范围。 –

回答

2

有三种类型的内存或变量,像在你的函数中一样自动,静态和手动。自动持续,范围持续。静态是,如果你声明它是静态的:

static int i; 

它活着,而程序还活着。像全局变量一样。最后手动使用malloc并自由分配和释放内存。当然,你想要分配变量的地址返回前指针,像这样:

int * newPointer = &i; 

如果变量是静态的,将保持值通过函数调用。 代码避免了编译器警告有关通过指定的局部变量的地址指针,以便返回局部变量的地址,它可能是在其上运行某种像皮棉或夹板工具的好主意,这里是对这种tools

+1

您应该详细说明上述如何帮助OP。 – Carcigenicate

+1

'malloc()'和朋友管理_dynamically allocated_ memory,aka ** heap **。所有命名变量都必须“手动”定义,编译器只能“自动”处理临时数据。这不是“静态的”,而是全球性的,具有不同的联系。 – Olaf

+0

@Olaf当然,这里的问题是他正在声明指针,并将局部变量的地址赋值给指针,这是避免编译器'函数返回局部变量地址'的警告的好方法。寻找可以对代码进行静态分析并在这种情况下提供帮助的工具。 –

1

看讨论,newNum指针整数。所以newNum的目的是保存整数address

当你宣布

int * newNum; 

newNum然后指着一些垃圾。

以下各行,

*newNum = i; 

newNum内容将通过i被更新。但你忘了,newNum拥有一些垃圾地址?因此i的值被分配一些垃圾location

你可以试试这个:

/** 
* The following function will take an integer pointer from the caller. 
* Its callers duty to check whether the pointer is initialed or not. 
*/ 
void myfunc(int * newNum) { 
    // the content of the newNum pointer points will be updated 
    // as the memory address is sent here, we need not to return anything 
    *newNum = (*newNum) * (*newNum); 
} 

int main() { 
    int someInteger = 4; 
    int *ptr = &someInteger; 
    myfunc(ptr); 
    printf("Content of the pointer: %d", *ptr); 
    return 0; 
} 

你会得到输出一样,

内容指针:16

+0

@Blastfurnace,我错过了标记! Ty,编辑了我的答案。 –