如何分配具有连续内存的二维数组?如何使用它来访问行和列?举个例子

发布于 2024-08-21 15:02:01 字数 719 浏览 4 评论 0原文

我创建了一个二维数组,其内容如下

     int i,j,lx,ly;// lx,ly are the row and column respectively
     double** a;

     a=(double**) malloc((lx+2)*sizeof(double));

     a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));

     assert(a[0]); 

     for(i=1;i<lx+2;i++)
     {
       a[i]=a[i-1]+i*(ly+2);
     }

// 我为该数组中的所有元素分配了 0 值,如下

    for(i=0;i<(lx+2)*(ly+2);i++)
    {
      a[i]=0;
    } 

// 我打印出下面的所有元素

      for(i=0;i<(lx+2)*(ly+2);i++)
      {
         printf("position %d values %d\n",i,a[i]);
      } 

// 当我看到输出时,它显示了一个垃圾某个特定位置 13 处的值。我无法弄清楚..还请告诉我如何访问行和列,例如以 lx、ly 的形式访问第 7 列第 0 行和第 5 行第 6 列,如下所示我的代码

I have created a 2 d array which reads as follows

     int i,j,lx,ly;// lx,ly are the row and column respectively
     double** a;

     a=(double**) malloc((lx+2)*sizeof(double));

     a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));

     assert(a[0]); 

     for(i=1;i<lx+2;i++)
     {
       a[i]=a[i-1]+i*(ly+2);
     }

// I allocate a value of 0 to all the elements in this array as below

    for(i=0;i<(lx+2)*(ly+2);i++)
    {
      a[i]=0;
    } 

// I print out all my elements below

      for(i=0;i<(lx+2)*(ly+2);i++)
      {
         printf("position %d values %d\n",i,a[i]);
      } 

// When I see the output , it shows me a junk value at one particular position 13. I am unable to figure that out .. ALso kindly tell me how to access rows and columns like Eg to acces 7 th column row 0 and 5th row 6 th column in terms of lx, ly as shown in my code

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

独享拥抱 2024-08-28 15:02:01

你的方法肯定是朝着正确的大方向前进。

我认为:

a=(double**) malloc((lx+2)*sizeof(double));

通常是:

a = malloc(lx * sizeof(double *));

然后如果没有连续性要求,

a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));

在大多数程序中,这个: 看起来像:

a[0] = malloc(ly * sizeof(double));

最后,最后一行需要位于一个分配每个 a[i] 的循环中有它自己的 malloc'ed 空间。

但是,这不会创建连续的内存。为此,您需要进行大量分配,然后将其划分为行向量。因此,与其在循环中使用第二个 malloc,不如

double *t = malloc(lx * ly * sizeof(double));
for (i = 0; i < lx; ++i)
    a[i] = t + i * ly;

将其全部放在一起:

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

void arrayDemo(int lx, int ly)
{
  double **a;
  int i, j;

  a = malloc(lx * sizeof(double *));
  double *t = malloc(lx * ly * sizeof(double));
  for(i = 0; i < lx; ++i)
    a[i] = t + i * ly;

  for(i = 0; i < lx; ++i)
    for(j = 0; j < ly; ++j)
      a[i][j] = i*100 + j;
  for(i = 0; i < lx; ++i) {
    for(j = 0; j < ly; ++j)
      printf(" %4.0f", a[i][j]);
    printf("\n");
  }
}

int main(int ac, char **av)
{
  arrayDemo(atoi(av[1]), atoi(av[2]));
  return 0;
}

$ cc -Wall all.c
$ ./a.out 4 7
    0    1    2    3    4    5    6
  100  101  102  103  104  105  106
  200  201  202  203  204  205  206
  300  301  302  303  304  305  306

Your approach is definitely heading in the right general direction.

I think this:

a=(double**) malloc((lx+2)*sizeof(double));

would normally be:

a = malloc(lx * sizeof(double *));

And then without the contiguity requirement, this:

a[0]= (double*) malloc((lx+2)*(ly+2)* sizeof(double));

in most programs would look like:

a[0] = malloc(ly * sizeof(double));

And finally, that last line needs to be in a loop that assigns each a[i] with it's own malloc'ed space.

However, that won't create contiguous memory. To do that you will need to do that big allocation and then divide it up for the row vector. So, instead of the second malloc in a loop, perhaps something like:

double *t = malloc(lx * ly * sizeof(double));
for (i = 0; i < lx; ++i)
    a[i] = t + i * ly;

Putting it all together:

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

void arrayDemo(int lx, int ly)
{
  double **a;
  int i, j;

  a = malloc(lx * sizeof(double *));
  double *t = malloc(lx * ly * sizeof(double));
  for(i = 0; i < lx; ++i)
    a[i] = t + i * ly;

  for(i = 0; i < lx; ++i)
    for(j = 0; j < ly; ++j)
      a[i][j] = i*100 + j;
  for(i = 0; i < lx; ++i) {
    for(j = 0; j < ly; ++j)
      printf(" %4.0f", a[i][j]);
    printf("\n");
  }
}

int main(int ac, char **av)
{
  arrayDemo(atoi(av[1]), atoi(av[2]));
  return 0;
}

$ cc -Wall all.c
$ ./a.out 4 7
    0    1    2    3    4    5    6
  100  101  102  103  104  105  106
  200  201  202  203  204  205  206
  300  301  302  303  304  305  306
木緿 2024-08-28 15:02:01

此代码分配一个 10 x 5 的连续内存块,用递增双精度数对其进行初始化,然后打印由 x 和 y 索引的值:

#include "2d.h"

int main(void){

    unsigned int x,y;
    const unsigned int width = 10;
    const unsigned int height = 5;

    //we need an index into the x of the array
    double * index[width];

    //need the memory to store the doubles
    unsigned int memorySizeInDoubles = width * height;
    double * memory = malloc(memorySizeInDoubles * sizeof(double));

    //initialize the memory with incrementing values
    for(x = 0; x < memorySizeInDoubles; ++x){
        memory[x] = (double) x;
    }

    //initialize the index into the memory
    for(x = 0; x < width; ++x){
        index[x] = memory + height * x;
    }

    //print out how we did
    for(x = 0; x < width; ++x){
        for(y = 0; y < height; ++y){
           printf("[%u, %u]: Value = %f\n", x, y, index[x][y]);
        }
    }

    free(memory);

    return 0;
}

2d.h 文件应包含这些行:

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

int main(void);

注意: 内存创建的内容仅对于某些定义是连续的。内存在逻辑上是连续的,但不一定是物理上连续的。例如,如果该内存用于设备驱动程序,则 malloc 将不起作用。

This code allocates a 10 by 5 contiguous block of memory, initializes it with incrementing doubles, and then prints the values indexed by x and y:

#include "2d.h"

int main(void){

    unsigned int x,y;
    const unsigned int width = 10;
    const unsigned int height = 5;

    //we need an index into the x of the array
    double * index[width];

    //need the memory to store the doubles
    unsigned int memorySizeInDoubles = width * height;
    double * memory = malloc(memorySizeInDoubles * sizeof(double));

    //initialize the memory with incrementing values
    for(x = 0; x < memorySizeInDoubles; ++x){
        memory[x] = (double) x;
    }

    //initialize the index into the memory
    for(x = 0; x < width; ++x){
        index[x] = memory + height * x;
    }

    //print out how we did
    for(x = 0; x < width; ++x){
        for(y = 0; y < height; ++y){
           printf("[%u, %u]: Value = %f\n", x, y, index[x][y]);
        }
    }

    free(memory);

    return 0;
}

The 2d.h file should contain these lines:

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

int main(void);

Note: The memory created is only contiguous for some definitions. The memory is logically contiguous, but not necessarily physically contiguous. If this memory is for a device driver for instance, malloc won't work.

最近可好 2024-08-28 15:02:01

一维数组

double my_array = malloc(sizeof(double) * size_x * sizeof(double) * size_y);

您可以创建一个将通过其访问的

(获取位置 x=28,y=12)

my_array[12 * size_x + 28];

,也可以像您一样创建一个二维数组,但您可以使用

double **my_array = (double**) malloc(15 * sizeof(double));

for(int i = 0 ; i < 25; i++)
   {
   my_array[i] = (double*) malloc(30 * sizeof(double));
   for (int j = 0 ; j < 12; j++)
      {
      my_array[i][j] = 1.2;
      }
   }

double my_double = my_array[12][28];

Either you create a single dimension array

double my_array = malloc(sizeof(double) * size_x * sizeof(double) * size_y);

which you will access by

(get position x=28, y=12)

my_array[12 * size_x + 28];

or you create a 2d array like you do, but you access it with

double **my_array = (double**) malloc(15 * sizeof(double));

for(int i = 0 ; i < 25; i++)
   {
   my_array[i] = (double*) malloc(30 * sizeof(double));
   for (int j = 0 ; j < 12; j++)
      {
      my_array[i][j] = 1.2;
      }
   }

double my_double = my_array[12][28];
旧伤慢歌 2024-08-28 15:02:01

在 C 中,要拥有一大块连续内存,您需要一个 malloc(),或者拥有一个静态分配的数组。由于您需要动态内存,因此需要malloc()。由于您需要所有内容都是连续的,因此您只需要一次调用它。

现在,调用应该是什么样子?如果我理解正确的话,您需要 lx 乘以 ly 值,每个值的大小为 sizeof(double),因此您需要 lx* ly*sizeof(double) 要分配的字节。

题外话:我更喜欢按如下方式编写 malloc() 调用:

#include <stdlib.h> /* for malloc's prototype */
T *pt; /* for any type T */
size_t n; /* need n objects of type T */

pt = malloc(n * sizeof *pt);

使用 sizeofsizeof *pt 而不是 sizeof(T)< /code> 的一个优点是,如果 pt 的类型发生变化,您无需更改 malloc() 调用。不强制转换 malloc() 的结果很好,因为这样整个 malloc() 调用就与类型无关,并且更容易键入和阅读。但请务必#include

因此,要为 n double 分配空间,您可以这样做:

double *pd = malloc(n * sizeof *pd);
if (pd != NULL) {
    /* malloc succeeded */
} else {
    /* malloc failed */
}

现在,在分配内存之后,您需要能够对其进行索引。假设您有 lx == 2ly == 3。您的内存看起来像:

    +---+---+---+---+---+---+
pd: | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+

pd[0]pd[1]pd[2]double与第一行对应的值,pd[3]pd[6] 是与第二行对应的 double 值。您应该能够推广这一观察结果,将给定的 x,y 索引对转换为一个能够正确索引到您的 pd 数组的数字。

In C, to have one chunk of contiguous memory, you need one malloc(), or have a statically allocated array. Since you want dynamic memory, you will need malloc(). Since you need everything to be contiguous, you will need only one call to it.

Now, what should the call look like? If I understood you correctly, you need lx times ly values, each with size sizeof(double), so you need lx*ly*sizeof(double) bytes to be allocated.

Digression: I prefer writing my malloc() calls as follows:

#include <stdlib.h> /* for malloc's prototype */
T *pt; /* for any type T */
size_t n; /* need n objects of type T */

pt = malloc(n * sizeof *pt);

Using sizeof with sizeof *pt instead of sizeof(T) offers an advantage that if the type of pt changes, you don't need to change the malloc() call. Not casting the result of malloc() is nice because then the whole malloc() call is type-agnostic, and is easier to type and read. Be sure to #include <stdlib.h> though.

So, to allocate space for n doubles, you can do:

double *pd = malloc(n * sizeof *pd);
if (pd != NULL) {
    /* malloc succeeded */
} else {
    /* malloc failed */
}

Now, after allocating memory, you need to be able to index it. Let's say you have lx == 2 and ly == 3. Your memory looks like:

    +---+---+---+---+---+---+
pd: | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+

pd[0], pd[1] and pd[2] are the double values corresponding to the first row, pd[3] to pd[6] are the double values corresponding to the second row. You should be able to generalize this observation to translate a given x,y index pair to one number that indexes into your pd array properly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文