如果必须返回i,以下代码(func1())是否正确?我记得在某处读到返回对局部变量的引用时存在问题.它与func2()有什么不同?
int& func1()
{
int i;
i = 1;
return i;
}
int* func2()
{
int* p;
p = new int;
*p = 1;
return p;
}
Run Code Online (Sandbox Code Playgroud) 好吧,我无法理解何时以及为什么需要使用分配内存malloc.
这是我的代码:
#include <stdlib.h>
int main(int argc, const char *argv[]) {
typedef struct {
char *name;
char *sex;
int age;
} student;
//Now I can do two things
student p;
//or
student *ptr = (student *)malloc(sizeof(student));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我可以使用时需要分配内存student p;?
我有以下测试代码,文件test.c:
#include <stdio.h>
int *func()
{
int i = 123;
return &i;
}
int main()
{
printf("%d\n", *func());
}
Run Code Online (Sandbox Code Playgroud)
如果我使用命令来编译它就可以了,
#include <stdio.h>
int *func()
{
int i = 123;
return &i;
}
int main()
{
printf("%d\n", *func());
}
Run Code Online (Sandbox Code Playgroud)
它将有以下警告信息:
gcc test.c -o test
Run Code Online (Sandbox Code Playgroud)
但可以输出结果:123
如果我使用命令:
warning: address of stack memory associated with local variable 'i'
returned [-Wreturn-stack-address]
return &i;
^
1 warning generated.
Run Code Online (Sandbox Code Playgroud)
将会有如下错误信息:
gcc -Werror test.c -o test
Run Code Online (Sandbox Code Playgroud)
现在我想使用-Werror选项,但我也想忽略与局部变量“i”警告关联的堆栈内存的地址。我应该怎么办?
我试图调用一个方法,该方法将生成一个2D char数组(字符串数组)并将其返回以在另一个函数中使用。
我的例子:
char ** example(void)
{
char *test[3];
int i;
for (i = 0; i < 3; i++) {
test[i] = malloc(3 * sizeof(char));
}
test[foo][bar] = 'baz'; // of course I would declare 'foo' and 'bar'
// ...
// ...
return test;
}
Run Code Online (Sandbox Code Playgroud)
然后,我希望能够如下使用数组:
void otherMethod(void)
{
char ** args = example();
// do stuff with args
}
Run Code Online (Sandbox Code Playgroud)
问题是这会产生错误:
警告:与局部变量“ test”关联的堆栈内存地址已返回[-Wreturn-stack-address]
我可以通过test在全局范围(而不是局部范围)中进行定义来解决此问题,但是我宁愿不要这样做,因为它看起来很杂乱,尤其是如果我要拥有其中几个。
有没有一种方法可以在C中创建和返回字符串数组,而无需全局定义它?
我编写了以下简单的程序,对 0 到 9 的数字进行求和:
#include <stdio.h>
#include <stdlib.h>
int* allocArray() {
int arr[10];
return arr;
}
int main(void){
int* p;
int summe = 0;
p = allocArray();
for(int i = 0; i != 10; ++i) {
p[i] = i;
}
for(int i = 0; i != 10; ++i) {
summe += p[i];
}
printf("Sum = %d\n", summe);
}
Run Code Online (Sandbox Code Playgroud)
该代码编译并提供预期结果“45”。但是我收到以下警告:“返回与局部变量‘arr’关联的堆栈内存地址”。我究竟做错了什么?