程式1:
int main ()
{
int a[5][5];
int (*p)[4];
p = a;
printf ("a_ptr=%#p,p_ptr=%#p\n", &a[4][2], &p[4][2]);
printf ("%p,%d\n", &p[4][2] - &a[4][2], &p[4][2] - &a[4][2]);
return 0;
}
&p[4][2] - &a[4][2]的值为-4
程式2:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void GetMemory(char *p, int num) { p = (char *)malloc(num * sizeof(char)); }
char *GetMemory2(char *p, int num) {
p = (char *)malloc(num * sizeof(char));
return p;
}
void GetMemory3(char **p, int num) {
*p = (char *)malloc(num * sizeof(char));
}
int main() {
char *str1 = NULL;
char *str2 = NULL;
// GetMemory▒istr▒C10▒j;
str1 = GetMemory2(str1, 10);
GetMemory3(&str2, 10);
strcpy(str1, "hello");
strcpy(str2, "world");
printf("%s %s\n", str1, str2);
free(str1);
free(str2);
return 0;
}
函數指標
程式3:
#include <stdio.h>
#include <string.h>
char* fun(char* p1, char* p2) {
int i = 0;
i = strcmp(p1, p2);
if (0 == i) {
return p1;
} else {
return p2;
}
}
int main() {
char* (*pf)(char* p1, char* p2);
pf = &fun;
(*pf)("aa", "bb");
return 0;
}
但
void Function()
{
printf("Call Function!\n");
}
int main()
{
void (*p)();
*(int*)&p=(int)Function;
(*p) ();
return 0;
}
以上程式是不會過關的,需要思考的是原本宣告成指向return void的函數的指標,如何轉型成指向return int的函數的指標。