[英]Multidimensional array with enum type and casting them into unsigned char array
這是代碼。
#include <stdio.h>
#define N 3
#define COPY(a, i) (a[(i)]) = (a[((i)+1)])
enum course {BTP300 = 1, OOP244, OOP344, OOP444, BTP400 = 8, BTP500};
typedef enum course Course;
void display(void* a, int n) {
int i;
unsigned char* c = (unsigned char*)a;
for (i = 0; i < n; i++)
printf("%d ", c[i]);
printf("\n");
}
void process(void *c, int n, int s) {
int i, j;
unsigned char* a = (unsigned char*)c;
for (i = 0; i < s * n; i++) {
unsigned char x = a[i];
for (j = 1; j < s - 1; j++, i++)
COPY(a, i);
a[++i] = x;
}
}
int main() {
Course array[2][N] = {BTP300, BTP400, BTP500, OOP244, OOP344, OOP444};
display(array[1], sizeof(Course)*N);
display(array[0], sizeof(Course)*N);
process(array[0], N, sizeof(Course));
process(array[1], N, sizeof(Course));
display(array[1], sizeof(Course)*N);
display(array[0], sizeof(Course)*N);
return 0;
}
2 0 0 0 3 0 0 0 4 0 0 0
1 0 0 0 8 0 0 0 9 0 0 0
0 0 0 2 0 0 0 3 0 0 0 4
0 0 0 1 0 0 0 8 0 0 0 9
現在,在投射指針時看起來像是在發揮作用。 我最初以為雖然創建了內存,但是在數組中您只是跳過了。 所以我仍然會得到234。 我得到1byte char。
0 2
1 0
2 0
3 0
這也被打印出來。
這是怎么回事?
枚舉值在C中為int
類型,在大多數平台上int
通常為四個字節(32位)。 因此,嘗試以char
訪問值不會給您預期的結果。
對於display
函數,您不需要乘以sizeof(Course)
,條目數為N
因此這是您應提供給函數的大小:
display(array[1], N);
當然,您應該使用int
作為單獨的值,或者使用Course
。
您還需要重新考慮process
功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.