Skip to content

Commit

Permalink
[array] add fake 2d array example
Browse files Browse the repository at this point in the history
  • Loading branch information
luhuadong committed Jul 26, 2023
1 parent 2605be7 commit deceefa
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
30 changes: 30 additions & 0 deletions datatype/array/fake_2d_array.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#include <stdio.h>
#include <stdlib.h>

#define ROWS 3 // 二维数组的行数
#define COLS 4 // 二维数组的列数

int main()
{
int arr[ROWS * COLS]; // 一维数组
int (*arr2d)[COLS]; // 二维数组指针

arr2d = (int (*)[COLS]) arr; // 将一维数组的地址赋给二维数组指针

// 通过指针方式访问二维数组的元素,并进行赋值
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
arr2d[i][j] = i * COLS + j;
}
}

// 打印二维数组的元素
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d\t", arr2d[i][j]);
}
printf("\n");
}

return 0;
}
16 changes: 12 additions & 4 deletions datatype/array/makefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
all:
gcc access_array.c -o access_array
gcc dynamic_array.c -o dynamic_array
CC := gcc
CFLAGS := -std=gnu17 -Wall -Wextra
SRCS := $(wildcard *.c)
EXES := $(SRCS:.c=)

all: $(EXES)

%: %.c
$(CC) $(CFLAGS) -o $@ $^

clean:
rm access_array dynamic_array
rm -f $(EXES)

.PHONY: all clean

0 comments on commit deceefa

Please sign in to comment.