我應該對代碼寫一個很長的解釋,但解釋已經在下面的代碼中,所以我想我的問題是:我如何讓它作業而不必 malloc 然后釋放它?或者基本上在這種情況下寫這個的正確方法是什么?
#include <stdio.h>
#include <malloc.h>
struct d {
int f;
};
struct d* rr() {
struct d* p = malloc(sizeof (struct d*));
p->f = 33;
return p;
}
void rr2(struct d* p) {
p = malloc(sizeof (struct d*));
p->f = 22;
}
int main()
{
//works..
struct d* g;
g = malloc(sizeof (struct d));
g->f = 45;
printf("[%i]", g->f);
//works..
g = rr();
printf("[%i]", g->f);
//below, both are same, except in this first case, g is allocated then freed..
//works..
free(g);
rr2(g);
printf("[%i]", g->f);
//doesn't work..
struct d *q;
rr2(q);
printf("[%i]", q->f);
return 0;
}
uj5u.com熱心網友回復:
對于這兩個功能的初學者
struct d* rr() {
struct d* p = malloc(sizeof (struct d*));
p->f = 33;
return p;
}
和
void rr2(struct d* p) {
p = malloc(sizeof (struct d*));
p->f = 22;
}
有一個錯字。看來你的意思
struct d* p = malloc(sizeof (struct d));
^^^^^^^^
和
p = malloc(sizeof (struct d));
^^^^^^^^^
或者
struct d* p = malloc(sizeof ( *p ));
^^^^^
和
p = malloc(sizeof ( *p) );
^^^^^
至于這個功能
void rr2(struct d* p) {
p = malloc(sizeof (struct d*));
p->f = 22;
}
然后在這個電話中
struct d *q;
rr2(q);
指標q按值傳遞給函式。因此該函式處理指標的副本q。更改函式內的副本不會反映在原始指標上q。它保持不變。
要使代碼正常作業,您必須通過參考傳遞指標(間接通過指向它的指標)。在這種情況下,函式看起來像
void rr2(struct d **p) {
*p = malloc(sizeof (struct d ));
( *p )->f = 22;
}
并被稱為
rr2( &q );
至于這個代碼片段
free(g);
rr2(g);
printf("[%i]", g->f);
然后它只是呼叫未定義的行為,因為在這個陳述句中
printf("[%i]", g->f);
可以訪問已釋放的記憶體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480152.html
上一篇:有什么方法可以從不同物件的元組(但從同一個基類派生)構建指標陣列?
下一篇:智能指標的二叉搜索樹
