[英]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.