编程新手,不懂 2D/3D 数组

发布于 2024-09-07 09:45:35 字数 1983 浏览 2 评论 0原文

大家好,我对编程基本上是新手。我决定尝试开始使用 C(不是 C++ 或 C#),到目前为止我做得很好。在我开始犹豫之前,我已经成功地了解了二维数组。虽然我认为我广泛理解 2D 整数数组,但我当然不理解 3D 字符串数组。

我正在通过采用这些技术并将其应用到我创建的实际程序中来学习,汇率“计算器”基本上要求用户选择一种基础货币,然后以美元打印其价值。不涉及数学,我只是用谷歌搜索欧元/美元之类的东西,并在下面讨论的数组中手动​​设置值。

但这就是我陷入困境的地方。我认为学习多维数组的最佳方法是实际应用该理论,因此这是我到目前为止所输入的内容(为了简洁起见,我省略了程序的其他函数(包括调用此函数的代码)) :

 char currencies[5][3][4] = {
    {'1','2','3','4','5'},
    {'GBP','EUR','JPY','CAD','AUD'},
    {'1.5','1.23','0.11','0.96','0.87'}
};

int point, symbol, value;

displayarraycontents()
{
    for(point=1;point<5;point++){
        for(symbol=1;symbol<5;symbol++){
            for(value=1;symbol<5;symbol++)
                printf("%s ", currencies[point][symbol][value]);
            printf("\n");
        }}

}

因为 C 没有字符串数据类型,所以构建字符串数组完全让我感到困惑。

为什么选择货币[5][3][4]?因为我总共存储了 5 种货币,每种货币都标有 3 个字母的符号(例如 EUR、CAD),其值最多为 4 位数字(包括小数点)。

我正在尝试显示此列表:

1 GBP 1.5
2 欧元 1.23
3日元0.11
4 加元 0.96
5 AUD 0.87

当我单击构建时,我在数组中指定值的行会突出显示,并显示以下警告的多个实例:

警告:隐式常量转换中溢出

...以及我打印的行数组的内容通过以下警告突出显示:

警告:格式 '%s' 需要类型 'char *',但参数 2 具有类型 'int'

运行代码后,程序的其余部分除了这个函数之外,它工作正常,它会产生“分段错误”或类似的错误。

有人可以帮我吗?任何帮助以及简单的 C 2D/3D 字符串数组初始化教程的链接将不胜感激! (我的两本书《K&R》和《Teach Yourself C》仅提供了不相关的模糊示例)

提前致谢!
-Ryan

编辑:使用结构更新代码:

struct currency {
    char symbol[4];
    float value[5];
};


void displayarraycontents(){

        int index;

        struct currency currencies[] {
            {"GBP", 1.50},
            {"EUR", 1.23},
            {"JPY", 0.11},
            {"CAD", 0.96},
            {"AUD", 0.87},};

}

我收到以下错误: main.c:99: 错误:嵌套函数被禁用,使用 -fnested-functions 重新启用
main.c:99: 错误:在“{”标记之前应有“=”、“,”、“;”、“asm”或“属性
main.c:100: 错误:预期为 ';'在“}”标记之前
main.c:100: 错误:',' 标记之前的预期表达式

在实际代码窗口本身中,每个符号都被标记为“意外标记”。

Hey everyone, I'm basically new to programming. I've decided to try and get started with C (not C++ or C#) and so far I've been doing pretty well. I managed to get far as two-dimensional arrays before I started to falter. While I think I broadly understand 2D integer arrays, I certainly don't understand 3D string arrays.

I'm learning by taking the techniques and applying them in an actual program I've created, an exchange rate "calculator" that basically takes asks the user to select a base currency then prints its value in USD. There's no maths involved, I simply googled stuff like EUR/USD and set the values manually in the array which I discuss below.

But here's where I'm getting stuck. I figure the best way to learn multi-dimensional arrays is to practically apply the theory, so here's what I've typed so far (I've omitted the other functions of my program (including the code which calls this function) for brevity):

 char currencies[5][3][4] = {
    {'1','2','3','4','5'},
    {'GBP','EUR','JPY','CAD','AUD'},
    {'1.5','1.23','0.11','0.96','0.87'}
};

int point, symbol, value;

displayarraycontents()
{
    for(point=1;point<5;point++){
        for(symbol=1;symbol<5;symbol++){
            for(value=1;symbol<5;symbol++)
                printf("%s ", currencies[point][symbol][value]);
            printf("\n");
        }}

}

Because C doesn't feature a string data type, building string arrays completely messes with my head.

Why currencies[5][3][4]? Because I'm storing a total of 5 currencies, each marked by a 3-letter symbol (eg EUR, CAD), which have a value of up to 4 digits, including the decimal point.

I'm trying to display this list:

1 GBP 1.5
2 EUR 1.23
3 JPY 0.11
4 CAD 0.96
5 AUD 0.87

When I click build, the line where I specify the values in the array is highlighted with several instances of this warning:

warning: overflow in implicit constant conversion

...and the line where I print the contents of the array is highlighted with this warning:

warning: format '%s' expects type 'char *', but argument 2 has type 'int'

Upon running the code, the rest of the program works fine except this function, which produces a "segmentation error" or somesuch.

Could somebody give me a hand here? Any help would be greatly appreciated, as well as any links to simple C 2D/3D string array initialisation tutorials! (my two books, the K&R and Teach Yourself C only provide vague examples that aren't relevant)

Thanks in advance!
-Ryan

EDIT: updated code using struct:

struct currency {
    char symbol[4];
    float value[5];
};


void displayarraycontents(){

        int index;

        struct currency currencies[] {
            {"GBP", 1.50},
            {"EUR", 1.23},
            {"JPY", 0.11},
            {"CAD", 0.96},
            {"AUD", 0.87},};

}

I get the following errors:
main.c:99: error: nested functions are disabled, use -fnested-functions to re-enable
main.c:99: error: expected '=', ',', ';', 'asm' or 'attribute' before '{' token
main.c:100: error: expected ';' before '}' token
main.c:100: error: expected expression before ',' token

In the actual code window itself, every symbol is flagged as an "unexpected token".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

夕嗳→ 2024-09-14 09:45:35

在这种情况下,您实际上并不需要 3D 数组。事实上,由于您有一个值表,因此您所需要的只是一个一维数组。

棘手的部分是数组的每个元素需要存储两个内容:货币符号和相关的汇率。 C 有一种构建存储两种东西的类型的方法 - 它是 struct 机制。我们可以定义一个struct来保存单一货币:(

struct currency {
    char symbol[4];
    char value[5];
};

请注意,这不会创建一个变量;它会创建一个类型structcurrencychar 类似,只是我们自己定义了前者的含义)。

...我们现在可以创建一个包含 5 个这样的数组:

struct currency currencies[5] = { 
    {"GBP", "1.5" },
    {"EUR", "1.23" },
    {"JPY", "0.11" },
    {"CAD", "0.96" },
    {"AUD", "0.87" } };

要迭代它们并将它们打印出来,代码将如下所示:

void displayarraycontents(void)
{
    int point;

    for(point = 0; point < 5; point++)
    {
        printf("%d %s %s\n", point + 1, currencies[point].symbol, currencies[point].value);
    }
}

In this case, you don't actually want a 3D array. In fact, since you have a table of values, all you need is a 1D array.

The tricky part is that each element of the array needs to store two things: the currency symbol, and the associated exchange rate. C has a way of building a type that stores two things - it's the struct mechanism. We can define a struct to hold a single currency:

struct currency {
    char symbol[4];
    char value[5];
};

(Note that this does not create a variable; it creates a type. struct currency is analagous to char, except that we defined the meaning of the former ourselves).

...and we can now create an array of 5 of these:

struct currency currencies[5] = { 
    {"GBP", "1.5" },
    {"EUR", "1.23" },
    {"JPY", "0.11" },
    {"CAD", "0.96" },
    {"AUD", "0.87" } };

To iterate over them and print them out, the code would look like:

void displayarraycontents(void)
{
    int point;

    for(point = 0; point < 5; point++)
    {
        printf("%d %s %s\n", point + 1, currencies[point].symbol, currencies[point].value);
    }
}
十级心震 2024-09-14 09:45:35

您需要 a 来更正数组维度,并且还需要将字符串声明为字符串,而不是多字节字符常量:

char currencies[3][5][5] = {
    {"1","2","3","4","5"},
    {"GBP","EUR","JPY","CAD","AUD"},
    {"1.5","1.23","0.11","0.96","0.87"}
};

数组维度的逻辑是错误的 - 您想要的是 3 列,每列有 5 个条目,每个条目是一个5字节长的字符串。

您的 for 循环应该从 0 开始索引,而不是从 1 开始。

You need a to correct your array dimensions, and you also need to declare your strings as strings, not as multibyte character constants:

char currencies[3][5][5] = {
    {"1","2","3","4","5"},
    {"GBP","EUR","JPY","CAD","AUD"},
    {"1.5","1.23","0.11","0.96","0.87"}
};

Your logic for the array dimensions is wrong - what you want is 3 columns, each with 5 entries, each of which is a string 5 bytes long.

Your for loop should index from 0, not from 1.

糖粟与秋泊 2024-09-14 09:45:35

for 语句中还有一个问题:

for(point=1;point<5;point++)

数组中的第一项位于 0 位置,因此 for 语句应该是这样的:

for(point=0;point<5;point++)

There is also a oops in for statements:

for(point=1;point<5;point++)

First item in an array is in 0 position, so for statements should be like this:

for(point=0;point<5;point++)
灵芸 2024-09-14 09:45:35

在这里使用结构体而不是多维数组更有意义。

#include <stdio.h>

typedef struct Currency {
   const char* symbol;
   double value;
} Currency;

Currency CURRENCIES[] = {
   {"GBP", 1.5},
   {"EUR", 1.23},
   {"JPY", 0.11},
   {"CAD", 0.96},
   {"AUD", 0.87},
};
size_t NUM_CURRENCIES = sizeof(CURRENCIES) / sizeof(Currency);

int main()
{
   size_t index;

   for (index = 0; index < NUM_CURRENCIES; index++)
   {
      printf("%zu %s %.2f\n",
         index + 1, CURRENCIES[index].symbol, CURRENCIES[index].value);
   }

   return 0;
}

It would make more sense to use structs here rather than a multi-dimensional array.

#include <stdio.h>

typedef struct Currency {
   const char* symbol;
   double value;
} Currency;

Currency CURRENCIES[] = {
   {"GBP", 1.5},
   {"EUR", 1.23},
   {"JPY", 0.11},
   {"CAD", 0.96},
   {"AUD", 0.87},
};
size_t NUM_CURRENCIES = sizeof(CURRENCIES) / sizeof(Currency);

int main()
{
   size_t index;

   for (index = 0; index < NUM_CURRENCIES; index++)
   {
      printf("%zu %s %.2f\n",
         index + 1, CURRENCIES[index].symbol, CURRENCIES[index].value);
   }

   return 0;
}
花辞树 2024-09-14 09:45:35

应该是

char currencies[3][5][5] = {

因为它包含 3 个列表,每个列表包含 5 个字符串。

每个字符串最多有 4 个字符,但您需要额外的 NUL 字符,因此末尾有 5 个字符。

-- 编辑

您对数组访问感到困惑。使用您的数组定义(如上固定),将使用currency[data_type][index]来获取字符串。

  • 数据类型 = 0 ->索引
  • data_type = 1 ->符号
  • data_type = 2 -> 值

第一行的

{'1','2','3','4','5'},

是多余的。

固定代码:

 char currencies[2][5][5] = {
     {"GBP","EUR","JPY","CAD","AUD"},
     {"1.5","1.23","0.11","0.96","0.87"}
 };

 void displayarraycontents()
 {
    int index;
    for(index = 0;index < 5;index++) {
        printf("%i %s %s\n", index, currencies[0][index], currencies[1][index]);
    }
}

It should be

char currencies[3][5][5] = {

because it contains 3 lists containing 5 strings each.

Each string has a max of 4 characters, but you need the additional NUL character, so 5 at the end.

-- EDIT

You have the array access confused. Using your array definition (fixed as above) it would be currencies[data_type][index] to get a string.

  • data_type = 0 -> the index
  • data_type = 1 -> the symbol
  • data_type = 2 -> the value

the first line

{'1','2','3','4','5'},

is redundant.

Fixed code:

 char currencies[2][5][5] = {
     {"GBP","EUR","JPY","CAD","AUD"},
     {"1.5","1.23","0.11","0.96","0.87"}
 };

 void displayarraycontents()
 {
    int index;
    for(index = 0;index < 5;index++) {
        printf("%i %s %s\n", index, currencies[0][index], currencies[1][index]);
    }
}
青衫负雪 2024-09-14 09:45:35

在 C/C++ 中,您通常会从右到左读取数组维度,以了解编译器如何看待它。在这种情况下,您需要存储 4 个字符的字符串,每个字符串需要存储 5 个字符(包括尾随 \0),因此 [5] 将是数组大小。接下来,您将存储 5 个项目的组,因此中间值为 [5],最后,您将总共存储 3 组这些项目,因此为 [3]。所有这一切的最终结果是 charcurrency[3][5][5] = 。 。 .;

当然,正如其他地方所回答的,您需要对字符串值使用双引号。

In C/C++ you would normally read your array dimentions from right to left to get a good idea of how the compiler will see it. In this case, you need to store strings of 4 characters each which requires storage for 5 chars (to include the trailing \0) therefore [5] will be the array size. Next you are storing groups of 5 items, therefore the middle value will be [5] and finally, you are storing a total of 3 groups of these items, therefore [3]. The final result of all of this is char currencies[3][5][5] = . . .;

Of course, as replied elsewhere, you need to use the double quotes for string values.

百善笑为先 2024-09-14 09:45:35

如果你想用多维数组来解决这个问题,正如@Forrest所说,你需要[3][5][5]。这样看:在初始化器中,找到最外面的大括号:在最外面的大括号里面,有多少个元素? 3. 现在,每个元素(一层)有多少个元素? 5. 进一步深入,在每个元素中,您都有一个由 4 个元素组成的字符串,再加上一个终止符,同样 5.

第二个错误:单引号中只能有一个字符,例如 'a'< /代码>;这是 char 类型,相当于 ASCII 代码(在本例中为 97)。对于字符串,必须使用双引号("abc",相当于 {97, 98, 99, 0})。

第三个错误:循环。在一次打印一个字符串时,您实际上并没有迭代所有三个循环(因为 printf 实际上会为您执行其中一个循环) - 所以您应该只有 2 个循环(或者,效率较低,您可以保留所有三个循环,但一次只打印一个字符)。此外,您还需要注意循环限制;在每种情况下,您最多会增加 5 个维度,但是当您超出 [3] 维度时,这会给您带来运行时垃圾(在最好的情况下)或运行时崩溃(在最坏的情况下)。因此,类似这样的事情:

话又说回来,最里面的循环在变量使用方面不一致(复制粘贴错误)。

然而,几乎永远不需要编写这样的代码。您主要使用二维数组进行矩阵运算。像这样的东西应该只有一个一维数组,存储记录元素。

struct currency {
    int     id;
    char[4] symbol;
    float   value;
} currencies[5];

If you want to solve this with multi-dimensional arrays, as @Forrest says, you need [3][5][5]. Look at it this way: in the initializer, find the outermost braces: inside that, on the top level, how many elements are there? 3. Now, each of these elements (one level in), how many elements? 5. Drilling further down, inside each of those, you have a string of 4 elements, plus one for the terminator, again 5.

Second error: you can only ever have one character in single quotes, like 'a'; that's char type, and equivalent to ASCII code (97 in this case). For strings, you have to use double quotes ("abc", which is equivalent to {97, 98, 99, 0}).

Third error: loops. You are not actually iterating over all three loops while printing a string at a time (since printf will actually do one of the loops for you) - so you should only have 2 loops (or, less efficiently, you can keep all three loops, but then print only a character at a time). Also, you need to be aware of the loop limits; you are going up to 5 in each case, but this will give you runtime garbage (in the best case) or runtime crash (in the worst case) when you go out of your [3] dimension. Thus, something like this:

Then again, your innermost loop is inconsistent in your variable usage (copy-paste error).

However, there will almost never be need to write code like this. You mainly use 2D arrays for matrix operations. Something like this should only have a one-dimensional array, storing record elements.

struct currency {
    int     id;
    char[4] symbol;
    float   value;
} currencies[5];
以歌曲疗慰 2024-09-14 09:45:35

您不需要存储索引 (1-5),因为您可以访问数组 (0-4) 并因此知道索引。 您可以将其他值封装在一个结构体或两个单独的数组中,这将使您的数组降到应有的一维......这样,项目拥有正确的类型并且不会滥用二维数组。

2D 或 3D 区域不应填充不同类型的项目,当您拥有相同类型且具有逻辑 2D 或 3D 结构的项目时,就需要填充该区域。屏幕上的像素是需要 2D 结构的一个很好的例子,3D 图形中的坐标是需要 3D 结构的一个很好的例子。

You don't need to store the indices (1-5) as you can access the array (0-4) and thus know the indices. You can encapsulate the other values in a struct or two seperate arrays which gets your array(s) down to one dimension as it should be... In that way the items have proper types and you don't misuse two-dimensional arrays.

A 2D or 3D area shouldn't be filled with items that should be of a different type, it is needed when you have items that are of the same type and have a logic 2D or 3D structure. The pixels on your screen are a good example of something that needs a 2D structure, coordinates in a 3D graph are a good example of something that needs a 3D structure.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文