我正在尝试制作一个包含(在此示例中)要购买的商品名称的结构,并在一个矩阵中包含价格和应购买的重量的矩阵。这只是我正在尝试做的一个简单示例。
我用strcpy声明值只是因为我是这样学习的,如果不是最好的方法,我就不会这样做。

#include<stdio.h>
#include<string.h>
typedef struct Grocery_list{

    char item_name[2];
    double item_info[2][2];

}Grocery;


int main(){

Grocery market;
strcpy( market.item_name[0], "Apple");
strcpy( market.item_name[1], "Sugar");
strcpy( market.item_info[0][0],200); //apple weight
strcpy( market.item_info[1][0], 3); //apple price
strcpy( market.item_info[0][1], 300);
strcpy( market.item_info[1][1], 4);

printf("%f \n",martket.item_info[1][1]);

return 0;}


错误是

teste.C: In function ‘int main()’:
teste.C:14:27: error: invalid conversion from ‘char’ to ‘char*’ [-fpermissive]
 strcpy( market.item_name[0], "Apple");
                           ^
In file included from teste.C:2:0:
/usr/include/string.h:129:14: error:   initializing argument 1 of ‘char* strcpy(char*, const char*)’ [-fpermissive]
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
teste.C:15:27: error: invalid conversion from ‘char’ to ‘char*’ [-fpermissive]
 strcpy( market.item_name[1], "Sugar");
                           ^
In file included from teste.C:2:0:
/usr/include/string.h:129:14: error:   initializing argument 1 of ‘char* strcpy(char*, const char*)’ [-fpermissive]
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)
              ^
teste.C:16:35: error: cannot convert ‘double’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
 strcpy( market.item_info[0][0],200);
                                   ^
teste.C:17:34: error: cannot convert ‘double’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
 strcpy( market.item_info[1][0], 3);
                                  ^
teste.C:18:36: error: cannot convert ‘double’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
 strcpy( market.item_info[0][1], 300);
                                    ^
teste.C:19:34: error: cannot convert ‘double’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
 strcpy( market.item_info[1][1], 4);
                                  ^
teste.C:21:16: error: ‘martket’ was not declared in this scope
 printf("%f \n",martket.item_info[1][1]);
                ^


显然,我在Google上搜索了答案和解决方案,但是我尝试执行的所有操作都导致了其他错误,甚至是相同的错误。因为我一般都是编程新手,所以我不知道这些错误是什么意思。

先感谢您

最佳答案

三个问题:

您的结构没有字符串数组。它具有字符数组。您需要为item_name添加一个额外的维度才能拥有这样的数组:

typedef struct Grocery_list{

    char item_name[2][50];
    double item_info[2][2];

}Grocery;


另外,您正在使用strcpy尝试复制数值。此功能用于复制字符串。代替使用此功能,执行一个简单的分配:

market.item_info[0][0] = 200; //apple weight
market.item_info[1][0] = 3; //apple price
market.item_info[0][1] = 300;
market.item_info[1][1] = 4;


最后,您在printf语句中有一个错字:

printf("%f \n",martket.item_info[1][1]);


它应该是:

printf("%f \n",market.item_info[1][1]);

关于c - 矩阵在C中的结构中起作用吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38981029/

10-12 16:10