[英]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.