简体   繁体   English

使用动态内存分配来构建特定矩阵

[英]Using dynamic memory allocation to construct a specific matrix

Before anything else, my thanks to anyone who is reading this topic. 首先,感谢正在阅读本主题的任何人。 It's much appreciated. 非常感谢。

In my final project of a programming subject in university, I've been told to write a program that uses a single matrix, with the following "restrictions": 在我大学的编程课程的最后一个项目中,有人告诉我编写一个使用单个矩阵的程序,并带有以下“限制”:

  1. The user inputs an interval of years (example: 2017-2020) which will determine the number of lines of the matrix by using the formulae: 用户输入年份间隔(example: 2017-2020) ,它将使用以下公式确定矩阵的行数:

    NumberOfLines=(FinalYearGiven - InicialYearGiven) + 1;

  2. The matrix must have a fixed column number of 6. 矩阵的固定列号必须为6。

  3. The 1st column of each line will show the year. 每行的第一列将显示年份。
  4. The 2nd will show the number of days in february. 2号将显示2月的天数。
  5. The 3rd will show the number of days in the year. 第三天将显示一年中的天数。
  6. The 4th will show the number of hours in the year. 第4位将显示一年中的小时数。
  7. The 5th will show the number of minutes in the year. 第五位将显示一年中的分钟数。
  8. The 6th will show the number of seconds in the year. 第六位将显示一年中的秒数。

Last year I was instructed to do a program that multiplicated two inputed matrices and its allocation was as follows: 去年,我被指示去做一个程序,将两个输入矩阵相乘,其分配如下:

 double** multiplication_of_2_matrices(double **A, double **B, int lines1, int columns1, int lines2, int columns2)
    {
        int i, j, k;
        double **C; // Pointer to the resultant matrix, dynamically allocating the matrix in this function
        C = (double**)malloc(lines1 * sizeof(double*));
        for (i = 0; i<lines1; i++)
            C[i] = (double*)malloc(columns2 * sizeof(double));    
        for (i = 0; i < lines1; i++) 
        {
            for (j = 0; j < columns2; j++) 
            {
                C[i][j] = 0.0;
                for (k = 0; k < columns1; k++) 
                {
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }
        return C;
    }

My doubt consists in what can I do in this particular project to dynamically allocate the matrix. 我的疑问在于我可以在这个特定项目中做什么以动态分配矩阵。 Can I use the form of allocation specified above or need to use another form? 我可以使用上面指定的分配形式还是需要使用其他形式?

Yes you can this exactly the same way of allocation but only thing is you will now want to use the int elements rather than double. 是的,您可以使用完全相同的分配方式,但是唯一的事情是您现在将要使用int元素而不是double。

The steps will be precisely 步骤将是精确的

  • After you get the numberOfLines you will allocate the dynamic jagged array. 获得numberOfLines您将分配动态锯齿状数组。

  • While doing that two things 同时做两件事

    1. Don't cast the return value of malloc . 不要转换malloc的返回值。 It's unnecessary. 没必要
    2. Also free the dynamically allocated memory. 同时free动态分配的内存。
 unsigned int **c = malloc(sizeof *a*numberOfLines); if (c == NULL){ fprintf(stderr,"Error in allocation"); exit(1); } for(size_t i = 0; i< numberOfLines; i++){ c[i] = malloc(sizeof *a[i]*NUMCOLS); if( c[i] == NULL){ fprintf(stderr,"Error in allocation"); exit(1); } } ... return c; 
  • Use magic numbers for the constants like 6 . 对像6这样的常数使用幻数。 #define NUMCOLS 6 . #define NUMCOLS 6 (not mandatory - you can pass it as some parameters also). (不是强制性的-您也可以将其作为某些参数传递)。 Just make sure that it is not changed accidentally. 只要确保它不会意外更改即可。

  • I have used unsigned here because none of the data that you are going to store will be negative. 我在这里使用了unsigned ,因为您要存储的数据都不会为负。

Few modification that has been pointed out $ 指出了很少的修改$

As unsigned int 's size may vary system-wise (it is not true that unsigned int will have 32 bits at least), it is better to use this small trick to ensure maximum sized type. 由于unsigned int的大小可能会因系统而异(unsigned int至少具有32位是不正确的),因此最好使用此小技巧来确保最大大小的类型。

#if sizeof(unsigned int) < 4 
typedef unsigned long mydata; 
#else 
typedef unsigned int mydata; 
#endif

Also another point is instead of the fragmented memory you can do this to get a 2d array not jagged array. 还有一点是,您可以执行此操作以获取二维数组而不是锯齿状数组,而不是零散的内存。

mydata (*a)[NUMCOLS] = malloc(sizeof *a*numberOfLines);
if (a == NULL){
    fprintf(stderr,"Error in allocation");
    exit(1);
} 
...
return a;

You can do it another way also where you allocate the total number of elements all at one. 您也可以用另一种方法来完成,即一次分配全部元素的总数。 And then access the positions accordingly. 然后相应地访问职位。

mydata *a = malloc(sizeof *a * NUMCOLS * numberOfLines);
if (a == NULL){
    fprintf(stderr,"Error in allocation");
    exit(1);
} 
..
..

//accessing a[i][j] will be i*NUMCOLS+j 

$ PeterJ_01 pointed out these details and suggested the scope of another way to achieve the allocation $ PeterJ_01指出了这些细节,并提出了另一种实现分配的方式的范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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