简体   繁体   中英

How to access elements in double pointer style matrix

double **matrix = NULL;
matrix = (double **)malloc(sizeof(double *) * N);   // N is the size of the square matrix

for(int i=0; i<N; i++)
{
   matrix[i] = (double *)malloc(sizeof(double)*N);
}

// Works good up to the next part
for(int i=0; i<N; i++)
{
   for(int j=0; j<N; j++)
   {
      printf("Value: %f", matrix[i][j]);
   }
}

I'm trying to create a two dimensional array of doubles by using the method above (create an array of pointers, and then each pointer gets an array of doubles). However, as soon as I try to print the first element matrix[0][0], I get a seg fault. I've seen some other posts that do almost the same thing, except I can't get mine to work.

Syntax-wise, there is nothing wrong with your code. Either you aren't showing the whole code, or (less likely) the program ran out of memory and you didn't check the result of malloc to find out about that.

Program design-wise, you shouldn't use the fragmented pointer to pointer syntax; it creates N arrays all over the heap, instead of one single true 2D array allocated in adjacent memory cells. Heap fragmentation is bad for program performance and may cause various other problems (depending on system).

Casting the result of malloc is pointless in C. On old C compilers, it is even harmful.

You don't give the items of the array any values before printing them. To set them all to zero, either use memset or replace malloc with calloc.

You should fix the above mentioned issues and rewrite your code to this:

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

double (*matrix)[N];  // an array pointer
matrix = calloc(1, sizeof(double[N][N])); // pointing at one true 2D array

if(matrix == NULL)
{
  // handle error
}


for(int i=0; i<N; i++)
{
  for(int j=0; j<N; j++)
  {
    printf("Value: %f", matrix[i][j]);
  }
}

Hi I have this c++ file and it works well till the end with g++ compiler.

#include <cstdio>
#include <cstdlib>

using namespace std;

int main(){
    int N = 10;
    double **matrix = NULL;
    matrix = (double **)malloc(sizeof(double *) * N);   // N is the size of the square matrix

    for(int i=0; i<N; i++)
    {
        matrix[i] = (double *)malloc(sizeof(double)*N);
    }

    for(int i=0; i<N; i++)
    {
        for(int j=0; j<N; j++)
        {
            printf("Value: %f", matrix[i][j]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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