我在寫這個程序來練習C語言編程,這是我的代碼:C編程:鑄造「無效指針」指向結構
#include <stdio.h>
#include <stdlib.h>
struct s1 {
int i;
void * p;
};
static struct s1 *dmk;
int main(void) {
int tong(int a, int b);
int (*tinh)(int,int);
struct s2 {
int num;
int (*cal)(int a, int b);
};
if(dmk->p == NULL)
{
printf("NULL ALERT\n");
}
struct s2 *cl = dmk->p;
cl->cal = tong;
tinh = ((struct s2 *)(dmk->p))->cal;
printf("tinh 2, 4 ra %d\n",tinh(2,4));
puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */
return EXIT_SUCCESS;
}
int tong(int a, int b)
{
return a + b;
}
當我編譯它,它沒有表現出任何錯誤或警告。但是當我運行程序時,終端告訴我「核心轉儲」並沒有顯示任何結果接受「NULL ALERT」。誰能解釋我爲什麼失敗?非常感謝。
在我引用的陳述中用' - >'調用UB是個問題。編碼器方面出現「*失敗*」。 @ T.J.Crowder – alk
實際上'dmk' **被**初始化,因爲它是一個全局變量。問題:它是一個_null pointer_。 – Olaf
@Olaf:正確,修正,謝謝。 – alk