世紀(jì)佳緣網(wǎng)站開發(fā)語言關(guān)鍵字是什么意思
C語言中指針作為形參傳遞時(shí),func(*a, *b)
這種形式的話,是無法通過簡(jiǎn)單的 a=b
來修改的,在函數(shù)體內(nèi)a的地址確實(shí)被修改成b的地址了,但是當(dāng)函數(shù)執(zhí)行結(jié)束時(shí),a的地址會(huì)重新回到原本的地址里面,這邊是由于函數(shù)執(zhí)行結(jié)束,函數(shù)的棧地址被釋放了,若是要獲取a修改的地址可以采用一下兩種形式獲取:
形式1:return addr;
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>static int * test(int*a,int*b)
{a = b;return a;
}
int main(int argc, char *argv[])
{int *a = NULL;int te = 10;int *b = &te;a = test(a,b);printf("a=%d",*a);return 0;
}
形式2:采用二級(jí)指針的形式,func(**a,*b)
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>static void test(int**a,int*b)
{*a = b;
}
int main(int argc, char *argv[])
{int *a = NULL;int te = 12;int *b = &te;test(&a,b);//傳入一級(jí)指針a的地址printf("a=%d",*a);return 0;
}
同樣的若是要修改指針a的內(nèi)容,如果a為空指針在函數(shù)內(nèi)調(diào)用 *a=*b;
就會(huì)造成段錯(cuò)誤,
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <malloc.h>static void test(int*a,int*b)
{*a = *b;
}
int main(int argc, char *argv[])
{int *a = NULL;int te = 12;int *b = &te;test(a,b);printf("a=%d",*a);return 0;
}
野指針不會(huì)有這個(gè)問題,因?yàn)橐爸羔槙?huì)被隨機(jī)的分配一塊內(nèi)存空間,但是實(shí)際使用中仍不建議這樣使用,使用野指針操作,可能會(huì)踩到其他內(nèi)存空間造成莫名其妙的死機(jī),并且很難排插問題。