【问题标题】:Assigning a value to a specific column in a multidimensional array (C)为多维数组中的特定列赋值 (C)
【发布时间】:2017-06-08 14:54:23
【问题描述】:

我正在尝试找到一种方法将特定列分配给多维数组中的特定值

根据下文,我知道如何手动分配它并通过 for 循环。

有没有更简单的方法来做这件事?谢谢

#include < stdio.h >
double Test1[4][5];
double a0, a1, a2, a3;

int main() {
  //Assigning one column in a specific row manually
  Test1[1][1] = 1;
  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  int row = sizeof(Test1) / sizeof(Test1[0]);
  printf("rows  %d \r\n", row);
  int column = sizeof(Test1[0]) / sizeof(Test1[0][0]);
  printf("cols  %d \r\n", column);

  int L;
  double a;
  //Assigning one column in all rows to one
  for (L = 0; L < row; L = L + 1) {
    Test1[L][1] = 1;
  }

  a0 = Test1[0][1];
  a1 = Test1[1][1];
  a2 = Test1[2][1];
  a3 = Test1[3][1];

  printf("a0  %f \r\n", a0);
  printf("a1  %f \r\n", a1);
  printf("a2  %f \r\n", a2);
  printf("a3  %f \r\n", a3);

  return 0;
}

【问题讨论】:

  • 将你的循环封装成一个函数是,恕我直言,唯一的方法
  • 感谢您的反馈。
  • 为什么要打印\r\n?只需使用\n,如果需要,转换将自动完成。你的在 Windows 上会变成\r\r\n

标签: c arrays


【解决方案1】:

没有设置二维数组列的标准函数。在 C 中,多维数组有点像幻觉。它们编译成一维数组。下面是一些代码来演示将值展开为一维数组:

#include <stdio.h>

int main(){
    int test[10][2] = {0};
    //point to the 1st element
    int * p1 = &test[0][0];

    //20th position is the 9th row, 2nd column
    p1[19] = 5;

    //9th element is the 5th row, 1st column
    int * p2 = p1 + 8;
    *p2 = 4;

    printf("Value set to 5: %d\n",test[9][1]);
    printf("Value set to 4: %d\n",test[4][0]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多