简体   繁体   English

在c中打印二维数组

[英]printing two dimensional array in c

I am trying to define a two dimensional array by initially defining elements for 5 x 2 matrix and then I am defining again the elements for 6th row. 我试图通过最初为5 x 2矩阵定义元素然后再为第六行定义元素来定义二维数组。 But when I try to print the elements of this matrix I am getting 0 and 5 for the last value. 但是,当我尝试打印此矩阵的元素时,最后一个值的值为0和5。 Tried same by defining elements again for 4th or 6th row but then it is working fine. 通过再次为第4行或第6行定义元素来进行相同的尝试,但随后工作正常。

#include<math.h>
#include<stdio.h>
main()
{
  int arr[ ][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
  int i, j;
  arr[5][0]=61; arr[5][1]=62;
  for (i=0;i<=5;i++)
  {
    for (j=0;j<=1;j++)
    {
      printf ("%d \n", arr[i][j]);
    }
  }
}

Your initialised array is given exactly enough memory to hold the specified data values. 您的初始化数组将获得足够的内存来容纳指定的数据值。 So 所以

int arr[ ][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};

creates the array as int arr[5][2] and then the line 创建数组为int arr[5][2] ,然后创建该行

arr[5][0]=61; arr[5][1]=62;

exceeds the array bounds. 超出数组范围。 The maximum index is [4][1] because array indexing is 0 based. 最大索引为[4][1]因为数组索引基于0 If you want to add another element you should specify 如果要添加其他元素,则应指定

int arr[6][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};

and then this line will work. 然后这条线将起作用。

arr[5][0]=61; arr[5][1]=62;

An alternative would be to use malloc() to allocate memory for the array, and then if you want to add another row you can use realloc() , and this shows how to make a flexible array. 一种替代方法是使用malloc()为该数组分配内存,然后,如果要添加另一行,则可以使用realloc() ,这显示了如何制作一个灵活的数组。

#include <stdio.h>
#include <stdlib.h>

#define COLUMNS 2
#define ROWS 5

typedef int rowtype[COLUMNS];

int main() {
    int i, j;
    rowtype *array = malloc(ROWS * sizeof(rowtype));
    if (array == NULL)
        return -1;

    for (j=0; j<ROWS; j++)
        for (i=0; i<COLUMNS; i++)
            array[j][i] = (j+1)*10 + (i+1);

    for (j=0; j<ROWS; j++) {
        for (i=0; i<COLUMNS; i++)
            printf ("%-4d", array[j][i]);
        printf ("\n");
    }

    printf("Add another row\n");
    array = realloc(array, (ROWS+1) * sizeof(rowtype));
    if (array == NULL)
        return -1;
    array[ROWS][0] = 61;
    array[ROWS][1] = 62;

    for (j=0; j<ROWS+1; j++) {
        for (i=0; i<COLUMNS; i++)
            printf ("%-4d", array[j][i]);
        printf ("\n");
    }

    free(array);
    return 0;
}

Program output: 程序输出:

11  12
21  22
31  32
41  42
51  52
Add another row
11  12
21  22
31  32
41  42
51  52
61  62

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

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