简体   繁体   English

具有枚举类型的多维数组,并将其转换为无符号char数组

[英]Multidimensional array with enum type and casting them into unsigned char array

here is the code. 这是代码。

#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;
}

The out put is: 输出是:

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

now what it seems like when casting the pointer the size comes into play. 现在,在投射指针时看起来像是在发挥作用。 I initially thought that though memory is created, in arrays you just jump over. 我最初以为虽然创建了内存,但是在数组中您只是跳过了。 so i would still get 234. but no. 所以我仍然会得到234。 I get 1byte char. 我得到1byte char。

0 2
1 0
2 0
3 0

And this gets printed too. 这也被打印出来。

whats going on? 这是怎么回事?

Enumeration values are of type int in C, and int is commonly four bytes (32 bits) on most platforms. 枚举值在C中为int类型,在大多数平台上int通常为四个字节(32位)。 So trying to access the values as char will not give you the expected result. 因此,尝试以char访问值不会给您预期的结果。

For the display function you do not need to multiply with sizeof(Course) , the number of entries is N so that is the size you should provide to the function: 对于display函数,您不需要乘以sizeof(Course) ,条目数为N因此这是您应提供给函数的大小:

display(array[1], N);

And of course you should be using either int for the separate values, or Course . 当然,您应该使用int作为单独的值,或者使用Course

And you need to rethink your process function as well. 您还需要重新考虑process功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM