简体   繁体   English

在C中访问2D数组的元素

[英]Access elements of a 2D array in C

I am getting a compiler error on something I thought was very straight forward and I don't fully understand. 我收到一些我认为非常直接的东西并且我不完全理解的编译器错误。 I have a 2D array and I want to compare one of the elements to another in a switch case. 我有一个2D数组,我想在开关盒中将其中一个元素与另一个元素进行比较。

#define REV_1    {'A','B','C','D'}
#define REV_2    {'E','F','G','H'}
#define REV_3    {'I','J','K','L'}
void myfunction()
{
    char Revisions[3][4] = {REV_1,REV_2,REV_3};
    char Rev1FirstLetter = Revisions[0][0];
    char Rev2FirstLetter = Revisions[1][0];
    char Rev3FirstLetter = Revisions[2][0];

    char doesntmatter = 5;
    switch(doesntmatter)
    {
        case Rev1FirstLetter:
        {
            [....]
            break;
        }
        case Rev2FirstLetter:
        {
            [....]
            break;
        }
        case Rev2FirstLetter:
        {
            [....]
            break;         
        }
    }

}

I am getting compiler errors saying 我收到编译器错误提示

Error: #268: declaration may not appear after executable statement in block 

on the lines 在线上

char Rev1FirstLetter = Revisions[0][0];
char Rev2FirstLetter = Revisions[1][0];
char Rev3FirstLetter = Revisions[2][0];

So do I have to use a pointer plus an offset to access these elements? 那么我是否必须使用指针和偏移量来访问这些元素? I know you can assign values INTO the array like 我知道你可以将值赋给数组像

Revisions[0][1] = 'F'; 

but I always thought that you could read values out of an array in the same way. 但我一直认为您可以用相同的方法从数组中读取值。 Sorry for the beginner question, but could someone please explain to me what the best way to access the data in this 2D array would be, whether it requires a pointer and offset, or another method? 对初学者的问题很抱歉,但是有人可以向我解释一下访问此2D数组中数据的最佳方法是什么,它是否需要指针和偏移量,或其他方法?

Assignments are ok. 分配还可以。 However, there is an issue with switch statement since case values are not constant expressions. 但是,由于case值不是常量表达式,所以switch语句存在问题。 If I change case values to constant expressions ie 'A', 'B' it compiles with c99 flag. 如果我将大小写值更改为常量表达式,即“ A”,“ B”,则会使用c99标志进行编译。

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

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