指针更改其值

时间:2019-03-08 22:39:53

标签: c pointers

我一直在尝试用C语言编写一个小的矩阵框架。问题在于,访问矩阵的组件正在以某种方式对其进行修改。您可以看到矩阵a在传递给matrix_scalar_multiply之后,其元素发生了怪异的变化。

您可以在jdoodle.com/a/13t7

上运行代码
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>


typedef struct Matrix
{
  int lines;            //number of lines
  int columns;          //number of columns
  float *numbers;       //elements of our matrix
} Matrix;

void
matrix_create (Matrix * a, const float *array, int lines, int columns)
{
  a->numbers = (float *) malloc (lines * columns);
  a->lines = lines;
  a->columns = columns;
  for (int i = 0; i < a->lines; i++)
    for (int j = 0; j < a->columns; j++)
      *(a->numbers + j + i * columns) = *(array + j + i * columns);
}

void
matrix_init (Matrix * a, int lines, int columns)
{
  a->numbers = (float *) malloc (lines * columns);
  a->lines = lines;
  a->columns = columns;
}

float *
matrix_element (Matrix * a, int line, int column)
{
  return a->numbers + column + line * a->columns;
}

int
matrix_scalar_multiply (float scalar, Matrix * a, Matrix * answer)
{
  matrix_init (answer, a->lines, a->columns);
  for (int i = 0; i < answer->lines; i++)
    for (int j = 0; j < answer->columns; j++)
      *matrix_element (answer, i, j) = *matrix_element (a, i, j) * scalar;
  return 0;
}

void
matrix_print (Matrix * a)
{
  for (int i = 0; i < a->lines; i++)
    {
      for (int j = 0; j < a->columns; j++)
    printf ("%f   ", *matrix_element (a, i, j));
      printf ("\n");
    }
  printf ("\n");
}

#include <stdio.h>

int
main ()
{
  Matrix a;
  Matrix b;
  float aa[4][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} };
  matrix_create (&a, aa, 4, 3);
  matrix_print (&a);

  matrix_scalar_multiply (3.0, &a, &b);
  matrix_print (&a);
  matrix_print (&b);
  return 0;
}

输出:

1.000000   2.000000   3.000000   
4.000000   5.000000   6.000000   
0.000000   0.000000   0.000000   
0.000000   0.000000   0.000000   

1.000000   2.000000   3.000000   
4.000000   5.000000   6.000000   
0.000000   0.000000   0.000000   
0.000000   0.000000   0.000000   

3.000000   6.000000   9.000000   
12.000000   15.000000   18.000000   
0.000000   0.000000   0.000000   
0.000000   0.000000   0.000000  

我已经尝试了很多事情,但是找不到为什么矩阵a一些元素被更改了。如果我评论matrix_init (answer, a->lines, a->columns);,一切都会顺利进行。但是,您会看到我什至没有在a中将matrix_init作为参数传递。

1 个答案:

答案 0 :(得分:1)

问题在这里。

a->numbers = (float *) malloc (lines * columns);

malloc分配字节,因此这分配了lines * columns字节。但是a->numbersfloats的数组,每个数组通常为4个字节。您只分配了25%的必要内存。为数组分配内存时,还必须包括元素的大小。

a->numbers = malloc (lines * columns * sizeof(float));

(旁注:it's unnecessary to cast the result of malloc

您可以使用*a->numbers的大小来为自己购买更多保护。然后,如果a->numbers的类型更改为double *,则分配仍然正确。

a->numbers = malloc (lines * columns * sizeof(*a->numbers));