【问题标题】:initializing a multidimensional array in a struct in c在c中的结构中初始化多维数组
【发布时间】:2021-12-14 21:37:01
【问题描述】:

嗨,我正在开发这个程序,它计算矩阵的各种计算(例如行列式和跟踪等),我想在结构中使用数组来创建矩阵。

在我的计算.h 头文件中,我有这个:

struct matrices {
     int matrix[3][3]; };

在我的计算.c 实现文件中,我有这个函数,它基本上在从用户获取整数输入后创建矩阵:

struct matrices creation (int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
     struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};
     return mmm;
}

但是,我收到错误消息error: extra brace group at end of initializer 定向到struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};

谢谢:)

【问题讨论】:

  • 您的意思是使用struct matrices mmm 吗?
  • 什么 sj95126 说,你的代码中没有称为矩阵的结构。
  • 是的,抱歉,我出于某种原因更改了我的代码,但忘记将其移过来。问题不在于名称差异@sj95126

标签: c multidimensional-array struct initialization


【解决方案1】:

在我的计算.c 实现文件中,我有这个函数 基本上在从 用户:

一般来说,为矩阵的每个位置设置一个单独的int 是不切实际的。如果是 30x30 矩阵呢?

相反,您使用索引将用户的每个值获取到所需的位置。

你的功能:

struct matrices creation (
    int  x, int x1, int x2,
    int x3, int x4, int x5,
    int x6, int x7, int x8 ) {
     struct matrices mmm = {{x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}};
     return mmm;
}

只需将 8 个int 填充到一个数组中,然后返回数组的一个副本,但与

相同
  matrix another = { {x1, x2, x3}, {x4, x5, x6}, {x7, x8, x9} };

示例

#include<stdio.h>
  
typedef int matrix[3][3];
int show(matrix);

int main(void)
{
  matrix one = {{1,2,3}, { 4,5,6}, { 7,8,9}};
  show(one);
  int x1,x2,x3,x4,x5,x6,x7,x8,x9;
  x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = x9 = 42;
  x5 = -4242;
  matrix another = { {x1, x2, x3}, {x4, x5, x6}, {x7, x8, x9} };
  show(another);
  return 0;
}

int show(matrix M)
{
    for ( int y=0;y<3;y+=1)
    {
        for( int x = 0;x<3;x+=1) printf("%6d ", M[y][x]);
        printf("\n");
    }
    printf("\n");
    return 0;
};

表演

     1      2      3 
     4      5      6 
     7      8      9 

    42     42     42 
    42  -4242     42 
    42     42     42 

【讨论】:

    【解决方案2】:

    似乎有一种类型。您的意思是代码 sn-p 声明中的结构 struct matrices 或结构 struct matrix

    如果忽略拼写错误,初始化将如下所示

    struct matrices {
         int matrix[3][3]; };
    
    struct matrices creation (int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
         struct matrices mmm = 
         { 
             {
                 { x,  x1, x2 }, 
                 { x3, x4, x5 }, 
                 { x6, x7, x8 }
             } 
          };
         return mmm;
    }
    

    或者如下方式

    struct matrices {
         int matrix[3][3]; };
         
    struct matrices creation(int x, int x1, int x2, int x3, int x4, int x5, int x6, int x7, int x8 ) {
         struct matrices mmm = 
         {
            .matrix = 
            {
                {x, x1, x2}, {x3, x4, x5}, {x6, x7, x8}
            }           
         };
         
         return mmm;
    }
    

    即聚合结构矩阵包含一个二维数组。 所以你需要多用一对牙套。

    【讨论】:

      猜你喜欢
      • 2011-04-14
      • 1970-01-01
      • 2021-02-03
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 2010-12-06
      相关资源
      最近更新 更多