C 語言練習程式(3) -- 指標相關程式集錦(2)


Posted by nathan2009729 on 2022-07-09

程式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的函數的指標。


#multi-dimension array #function pointer







Related Posts

Day04_Origami學習筆記

Day04_Origami學習筆記

Electric Lift Massage Tables: Elevate Your Massage Experience

Electric Lift Massage Tables: Elevate Your Massage Experience

SingleLiveEvent

SingleLiveEvent


Comments