像2D数组一样初始化2D数组 [英] Initializing a 2D array like a 1D array

查看:72
本文介绍了像2D数组一样初始化2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经像2D数组一样初始化了2D数组:

I have initialized a 2D array like a 1D array:

int a[2][3] = {1,2,3,4,5} 

这些值如何存储在此数组中?

How are the values stored in this array?

推荐答案

它们的分配如下:

1 2 3
4 5 0

零是因为您分配了一个大小为6的数组,但只指定了5个元素.

The zero is because you've allocated an array of size 6, but only specified 5 elements.

这称为行优先级".

您可能希望稍微规范一下您的代码.您的代码当前为:

You may wish to formalize your code slightly. Your code is currently:

int a[2][3] = {1,2,3,4,5};

如果使用gcc main.c -Wall -pedantic --std=c99进行编译,则会收到一些警告:

If you compile this with gcc main.c -Wall -pedantic --std=c99, you'll get a few warnings:

temp.c:2:17:警告:初始化程序[-Wmissing-braces]周围缺少括号

temp.c:2:17: warning: missing braces around initializer [-Wmissing-braces]

使用以下方法解决此问题

Resolve this using

int a[2][3] = {{1,2,3,4,5}};

这会给您一个新的警告:

This will give you a new warning:

temp.c:2:25:警告:数组初始化程序中的多余元素

temp.c:2:25: warning: excess elements in array initializer

使用以下方法解决此问题:

Resolve this using:

int a[2][3] = {{1,2,3},{4,5,0}};

这明确表示数据具有两行,每行三个元素.

This explicitly represents the data as having two rows of three elements each.

关于内存布局的一些想法

int a[2][3]将产生一个数组数组".这类似于指向数组的指针的数组",但与之不同.两者都有相似的访问语法(例如a[1][2]).但是只有对于数组数组",您才能使用a+y*WIDTH+x可靠地访问元素.

int a[2][3] will produce an "array of arrays". This is similar to, but contradistinct from, an "array of pointers to arrays". Both have similar access syntax (e.g. a[1][2]). But only for the "array of arrays" can you reliably access elements using a+y*WIDTH+x.

某些代码可能会阐明:

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

void PrintArray1D(int* a){
  for(int i=0;i<6;i++)
    printf("%d ",a[i]);
  printf("\n");
}

int main(){
  //Construct a two dimensional array
  int a[2][3] = {{1,2,3},{4,5,6}};

  //Construct an array of arrays
  int* b[2];
  b[0] = calloc(3,sizeof(int));
  b[1] = calloc(3,sizeof(int));

  //Initialize the array of arrays
  for(int y=0;y<2;y++)
  for(int x=0;x<3;x++)
    b[y][x] = a[y][x];

  PrintArray1D(a[0]);
  PrintArray1D(b[0]);
}

运行此命令,您将得到:

When you run this, you get:

1 2 3 4 5 6 
1 2 3 0 0 0 

打印b在我的机器上为零,因为它会运行到未初始化的内存中.结果是,使用连续内存可以使您做得很方便,让我们设置所有值而无需双循环.

Printing b gives zeros (on my machine) because it runs into uninitialized memory. The upshot is that using contiguous memory allows you to do handy things, let set all of the values without needing a double loop.

这篇关于像2D数组一样初始化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆