C語言指標使用小結

2021-07-04 20:44:10 字數 3705 閱讀 7195

小結下自己對c語言的指標使用的理解。

1,呼叫函式實現指標的申請與釋放。

在開發中需要重複使用某個指標型別,為此專門寫了一組處理該型別的函式,最基礎就是該指標型別的申請與釋放。常見的錯誤是通過傳入乙個一級指標來實現指標的申請或釋放。

測試用的資料型別

typedef struct _mystruct mystruct;

typedef struct _fileinfo fileinfo;

struct _mystruct

;

struct _fileinfo

;

mystruct *pmystruct;
測試函式_1

void create_mystruct_1(mystruct* pmystruct)
mystruct* create_mystruct_2( void )
void create_mystruct_3( mystruct** ppmystruct )
測試**

void main()

通過呼叫函式create_mystruct_1是不能為pmystruct1分配到記憶體的,還是老話題「函式呼叫是單向傳遞

的值傳遞

void swap(int x, int y)

void create_mystruct_4(mystruct* pms)
在main()函式中呼叫create_mystruct_1( pmystruct1 ),的確為形參pms動態分配了空間,pms指向了新分配空間的首位址(若malloc分配成功),但是這個形參的值不能反向傳遞給pmystruct1,而且還有個問題----在函式呼叫結束後,為pms分配的空間沒有得到釋放。

為了能通過函式呼叫成功地為指標變數分配記憶體,可以通過函式返回值或者傳遞二級指標的方法實現,當然了也可以使用全域性靜態變數(一般不採用),分別參考函式create_mystruct_2和create_mystruct_3.

同樣的道理,釋放指標時 通過呼叫下面的函式destory(pstring)也不能夠正確地釋放相應的指標pstring

void destory( char* pstr )

}

可以通過傳遞二級指標的方法來實現,如下:

void destory_2( char** ppstr )

}
呼叫destory_2(&pstring)釋放pstring指標。當然了,也可以使用預定義實現,如下:

#define freeif(p)  if(p)
釋放指標時,呼叫

freeif(pstring);
2,指向包含指標型別成員變數的結構體的指標的釋放

小標題的表達太長了,解釋下,這裡討論釋放指向結構體的指標變數,該結構體的成員變數中也包含指標型別。

在main函式中想要通過函式呼叫釋放pmystruct,按照上面一小節的討論,函式如下:

void destory_mystruct( mystruct **ppmystruct)

if( (*ppmystruct)->m_pfileinfo )
if( *ppmystruct )
}
void destory_fileinfo(fileinfo **ppfileinfo)
if( (*ppfileinfo)->m_pfilename )
if( (*ppfileinfo)->m_pfilepath )
if((*ppfileinfo)->m_preporttime)
if( *ppfileinfo )
}
當然了,也可以借助上面的巨集如下來寫:

void destory_fileinfo(fileinfo **ppfileinfo)
freeif( (*ppfileinfo)->m_pfilename );
freeif( (*ppfileinfo)->m_pfilepath );
freeif( (*ppfileinfo)->m_preporttime );
freeif( *ppfileinfo );
}
void destory_mystruct( mystruct **ppmystruct)

if( (*ppmystruct)->m_pfileinfo )
freeif( *ppmystruct );
}
3,指標陣列的指標分配與釋放

可以認為指標陣列的元素具有兩個屬性:陣列元素的屬性和指標型別的屬性。在定義和引用的時候作為一般的陣列元素來操作;在使用的時候遵照指標型別的特點。下面是個簡單的例子:

void main()
;

int i;

//malloc 

for(i=0;i<10;i++)

pmypa[i] = &i;

}

//printf

for( i=0;i<10;i++ )

//free

for( i=0;i<10;i++ )

}

c語言指標實驗心得與小結 C語言指標小結

最近發現自己c語言基礎還是很薄弱,去廣圖借了本 c指標原理揭秘 基於底層實現機制 深入學下指標大家想必都在windows中使用過ping 127.0.0.1 t,其中這些引數怎麼來的呢?看下面 include include int main int argc,char ar 我們平時直接就int ...

c語言指標問題小結

最近使用指標的時候遇到了一些問題,在這裡做乙個簡單的總結,加深下對指標的認識。陣列和指標大部分情況下可以互換使用,但是有些時候卻是必須得區別對待,否則一不小心就會出錯。比如下面四個test例子,test1是對的,test2是錯的,指標指向乙個位址的情況,因為getuartdata 返回乙個指標位址,...

C語言 指標小結(2)

6 返回指標值的函式 int main float p p search score,k printf d p float search float pointer 4 int n 7 指標陣列 比較適合用來指向若干個字串,比如儲存名字,用二維陣列的話會因為不知名字長度而浪費空間 int p 4 因...