Rah*_*ora 4 c algorithm malloc pointers data-structures
int main(){
int i = 0;
while(i < 2){
char str[10];
printf("%p\n", str); //outputs same address both the times
i++;
}
i = 0;
while(i<2){
char *str;
str = (char*)malloc(10*sizeof(char));
printf("%p\n", str); //outputs two different addresses
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,为什么在循环中声明相同的字符数组给出相同的地址,尽管变量被声明两次不同的时间.所以根据我的理解,它应该为它分配新的内存.但它每次都返回相同的地址.
在动态分配内存的第二个中,它返回两个不同的地址,这是可以理解的,因为malloc每次都会为我找到新的连续内存块.
但为什么它在第一种情况下打印相同的地址?
在您的第一个示例中, char str[10];局部变量仅在范围内有效{ }.范围结束后,变量被破坏并且内存被"释放".下一个alocation可以在同一个空间中,因为它是空的并且可用.
在第二个示例中,您使用malloc...在您调用free(或程序结束)之前,内存不会自动释放.