我有以下代码.
#include <iostream>
int * foo()
{
int a = 5;
return &a;
}
int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)
而代码只是运行而没有运行时异常!
输出是 58
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
我想知道如何malloc和free工作.
int main() {
unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
memset(p,0,4);
strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes**
cout << p;
free(p); // Obvious Crash, but I need how it works and why crash.
cout << p;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果答案在记忆水平上是深入的,如果可能的话,我将非常感激.
我是C的新手,我需要一些处理数组的方法的帮助.来自Java编程,我习惯于说int [] method()能够返回一个数组.但是,我发现使用C时,必须在返回数组时使用指针.作为一个新的程序员,我真的根本不理解这一点,即使我已经查看了许多论坛.
基本上,我正在尝试编写一个在C中返回char数组的方法.我将使用数组提供方法(让我们称之为returnArray).它将从前一个数组创建一个新数组并返回指向它的指针.我只是需要一些关于如何开始这个以及如何在从数组发出指针后读取指针的帮助.任何解释这个的帮助表示赞赏.
建议的数组返回函数的代码格式
char *returnArray(char array []){
char returned [10];
//methods to pull values from array, interpret them, and then create new array
return &(returned[0]); //is this correct?
}
Run Code Online (Sandbox Code Playgroud)
函数的调用者
int main(){
int i=0;
char array []={1,0,0,0,0,1,1};
char arrayCount=0;
char* returnedArray = returnArray(&arrayCount); ///is this correct?
for (i=0; i<10;i++)
printf(%d, ",", returnedArray[i]); //is this correctly formatted?
}
Run Code Online (Sandbox Code Playgroud)
我还没有测试过这个,因为我的C编译器目前还没有工作,但我想弄明白这一点
我是C的新手.我试图从一个函数返回一个二维数组.就是这样的
int *MakeGridOfCounts(int Grid[][6])
{
int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
int (*p)[6] = cGrid;
return (int*)p;
}
Run Code Online (Sandbox Code Playgroud)
我知道这会导致错误,需要帮助.谢谢