繁体   English   中英

为什么这需要进行malloc?

[英]Why does this need to be malloc'd?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    int * p = malloc(sizeof(int));
    *p = 10;
    *p += 10;
    printf("%d", *p);
}

如果它被分配了,它会给我正确的值,但是如果我将其声明为:它将给我一个总线错误:

int main(){
        int * p;
        *p = 10;
        *p += 10;
        printf("%d", *p);
    }

未初始化的指针就是这样。 初始化。 您期望它指向何处? 它的值是不确定的,读/写它会导致不确定的行为。

没有提及动态分配的内存( malloc ),但它必须是指有效的内存。 例如,这很好:

int main(void)
{
    int x;
    int *p = &x;
    *p = 10;
    *p += 10;
    printf("%d", *p);
}
#include<stdio.h>
#include<stdlib.h>
int main()
{

 int *ptr; 
 //*ptr=123;   Error here....Becuase it is like trying to store 
             //some thing into a variable without creating it first.

 ptr=malloc(sizeof(int)); // what malloc does is create a integer variable for you
                          // at runtime and returns its address to ptr,
                          // Which is same as if you assingned &some_variable 
                          // to ptr if it had been already present in your program.

 return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM