下面是代码。
#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。但不是。我得到1个字节的字符。
0 2
1 0
2 0
3 0这个也会被打印出来。
怎么回事?
发布于 2013-10-29 14:34:57
枚举值在C中是int类型,在大多数平台上int通常是四个字节(32位)。因此,试图以char的形式访问这些值不会得到预期的结果。
对于不需要与sizeof(Course)相乘的display函数,条目的数量是N,因此这是您应该提供给函数的大小:
display(array[1], N);当然,您应该使用int作为单独的值,或者使用Course。
你也需要重新考虑你的process函数。
https://stackoverflow.com/questions/19651190
复制相似问题