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


Posted by nathan2009729 on 2022-06-25

程式1:

#include <stdio.h>
int main()
{
    char a[10] = {"abcde"};
    printf("%c\n", a[2]);
}

程式1輸出:

c

程式2:

#include <stdio.h>
int main()
{
    struct TestStruct1{
      char c1;
      short s;
      char c2;
      int i;
    };
    struct TestStruct1 a;
    printf("c1 %p, s %p, c2 %p, i %p\n",
          (unsigned int)(void*)&a.c1-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a.s-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a.c2-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a.i-(unsigned int)(void*)&a);
    struct TestStruct2{
      char c1;
      char c2;
      short s;
      int i;
    };
    struct TestStruct2 a2;
    printf("c1 %p, c2 %p, s %p, i %p\n",
          (unsigned int)(void*)&a2.c1-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a2.c2-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a2.s-(unsigned int)(void*)&a,
          (unsigned int)(void*)&a2.i-(unsigned int)(void*)&a);
    #pragma pack(8)
    struct TestStruct4{
      char a;
      long b;
    };
    struct TestStruct5{
      char c;
      struct TestStruct4 d;
      long long e;
    };
    #pragma pack()
}

程式2輸出:

c1 (nil), s 0x2, c2 0x4, i 0x8
c1 0xfffffff8, c2 0xfffffff9, s 0xfffffffa, i 0xfffffffc

程式2牽扯到記憶體對齊。

程式3:

#include <stdio.h>
int main()
{
    int a[5] = {1,2,3,4,5};
    int *ptr = (int*)(&a+1);
    printf("%d %d\n", *(a+1), *(ptr-1));
}

程式3輸出:

2 5

這一題指出了a跟&a的不同。a+1代表移動的長度是1*sizeof(int)&a+1代表移動的長度是1*sizeof(a)

程式4:

#include <stdio.h>
int main()
{
    char a[5] = {'A','B', 'C', 'D'};
    //char (*p3)[5] = &a;
    char (*p3)[5]; 
    p3 = &a;
    char (*p4)[5] = a;
    printf("%c %c\n", *p3, *(p4+1));
    char (*p5)[3] = &a;
    char (*p6)[3] = a;
    printf("%c %c\n", *(p5+1), *(p6+1));
    char (*p7)[10] = &a;
    char (*p8)[10] = a;
    printf("%c %c\n", *(p7+1), *(p8+1));
    return 0;
}

程式4輸出:

3 8
6 6
= =

這是有問題的程式,輸出其實是不准的。使用cdecl,可以知道char (*p3)[5]的意思是
declare p3 as pointer to array 5 of char

程式5:

#include <stdio.h>
int main()
{
    struct Test{
      int Num;
      char *pcName;
      short sDate;
      char cha[2];
      short sBa[4];
    } *p;
    struct Test* address = p;
    printf("%p, %p, %ul, %u\n", p , p+0x1, (unsigned long)p+0x1, (unsigned int*)p+0x1);
}

程式5輸出:

0x7ffdcdcfb120, 0x7ffdcdcfb140, 3452940577l, 3452940580

這一題考驗了地址轉型後會如何處理。

程式6:

#include <stdio.h>

int main(){
  int a[4] = {1,2,3,4};
  int *ptr1 = (int*)(&a+1);
  int *ptr2 = (int*)((int)a+1);
  printf("%x, %x\n", ptr1[-1], *ptr2);
  return 0;
}

程式6輸出:

timeout: the monitored command dumped core

Reference

http://hackgrass.blogspot.com/2018/03/c-pointerint-foo-int-bar.html


#c pointer #c array







Related Posts

C語言-常用函式

C語言-常用函式

 Laradock (2) : 設定

Laradock (2) : 設定

Web開發學習筆記15 — 呼叫堆疊、同步與非同步、Promise、Async/Await、Conditional ternary operator

Web開發學習筆記15 — 呼叫堆疊、同步與非同步、Promise、Async/Await、Conditional ternary operator


Comments