使用指针到指针方法读取和打印矩阵

reading and printing matrix using pointer to pointer method

我编写了一个程序来读取和打印矩阵而不使用指针数组。该程序正确读取和打印矩阵,但在执行后崩溃。程序中没有警告。找不到程序有什么问题。我正在使用 Codeblock+mingw 另外,这种使用指针指向二维矩阵的指针的方法是否可以或有更好的方法?

#include <stdio.h>
#include <malloc.h>

int main()
{
   int numCols=2;
   int numRows=2;
   int *cols;
   int rowCount;
   int colCount;
   cols=(int*) malloc(numCols*sizeof(int));
   int **rows;
   rows= (int**) malloc(numRows*sizeof(cols));

   printf("Filling the rows and Columns\n");

   for(rowCount=0;rowCount<numRows;rowCount++)
   {
       printf("Fill Row Number %d\n",rowCount);
       for(colCount=0;colCount<numCols;colCount++)
       {
           printf("Enter the value to be read\n");
           scanf("%d",(*(rows+rowCount)+colCount));
       }
   }

   // Printing the values
     for(rowCount=0;rowCount<numRows;rowCount++)
   {
       printf("Print Row Number %d\n",rowCount);
       for(colCount=0;colCount<numCols;colCount++)
       {
           printf("%d\t",*(*(rows+rowCount)+colCount));
       }
       printf("\n");
   }
   free(rows);
   free(cols);
    return 0;
}

您没有以正确的方式分配内存。您的程序由于非法内存访问而崩溃。

Cols 数组有什么用;因为您永远不会在其中存储任何整数及其额外内容。第二行是一个数组 int* 而不是 int。分配二维数组的方法之一是

int** matrix;
matrix = (int **)malloc(sizeof(int *));
matrix[0] = (int *)malloc(sizeof(int) * c * r);

//To access elements
for(rowCount=0;rowCount<numRows;rowCount++)
{
   printf("Fill Row Number %d\n",rowCount);
   for(colCount=0;colCount<numCols;colCount++)
   {
       printf("Enter the value to be read %d %d \n", rowCount, colCount);
       scanf("%d",(*matrix+rowCount*numCols)+colCount);
   }
}
//free it as
free(matrix);

在 C 中按行分配和访问始终是一个好习惯,这样内存提取就不会成为瓶颈。

更新

是的,你可以这样分配内存。 rows= (int**) malloc(numRows * numCols * sizeof(int)); //Yes sizeof(int)

它在 C 中的完全合法语句。它将分配 numRows * numCols 大小的整数指针数组,每个元素的大小等于 sizeof(int)

在指针长度为 8 字节的 64 位平台上可能会出现问题。

即使假设它是 32 位平台,还有另一个问题。您将如何为您的预期目的取消引用 rows? rows[i] 将是一个指向整数的指针,即 int* 类型;但是在上面执行 scanf 会给你一个分段错误,因为 row[i] 将包含一些垃圾值,并可能导致你进入内存中一些不需要的区域。