我如何使用指针摆脱复制矩阵值的四个循环?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何使用指针摆脱复制矩阵值的四个循环?相关的知识,希望对你有一定的参考价值。

我想知道在再次执行外部for循环之前,如何使用指针来消除for循环的需要,该for循环逐个复制数组元素。该程序的目的是在不使用内置函数的情况下手动进行数组乘法。我要删除的for循环是两个将temp的值复制到temp1的嵌套循环。

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

int main()

    //defining variables
    int M, N, i, j, k, l, sum = 0;
    int R[5][5] =  0 ;
    int temp[5][5] =  0 ;
    int temp1[5][5] =  0 ;

    //Asking the user for the size of the array
    printf("Please enter the value of M that will be used to create an array of size M x M\nNote M must take a value between 1 and 5 inclusive\n");
    scanf_s(" %d", &M);
    while (M < 1 || M >5)      //Checking that the array has a size between 1 and 5
        printf("Please re enter size of the array M as a value between 1 and 5:\n");
        scanf_s("%d", &M);
    

    //Asking the user for the values in the array
    for (i = 0; i < M; i++)
    
        for (j = 0; j < M; j++)
            if (j == 0 && i == 0) 
                printf("\nPlease enter the first element in the array:\n");
                scanf_s("%d", &R[i][j]);
                temp[i][j] = R[i][j];
            
            else 
                printf("Please enter the next element in the array:\n");
                scanf_s("%d", &R[i][j]);
                temp[i][j] = R[i][j];
            
    

    //Asking the user for the power that the array multiplication will ocuur
    printf("\nTo what power would you like to calculate R to?\nNote this must be a positive interger\n");
    scanf_s("%d", &N);
    while (N <= 0) 
        printf("Please re-enter the power you would like to calculate to as a positive interger:\n");
        scanf_s("%d", &N);
    

    //Calculating the power of the array
    for (l = 0; l+1 < N; l++) 
        for (i = 0; i < M; i++) 
            for (j = 0; j < M; j++) 
                for (k = 0; k < M; k++) 
                    sum = sum + temp[i][k] * R[k][j];
                
                temp1[i][j] = sum;
                sum = 0;
                temp[i][j] = &temp1[i][j]
            
        
        for (i = 0; i < M; i++) 
            for (j = 0; j < M; j++) 
                temp[i][j] = temp1[i][j];
            
        
    

    //Printing the output array
    printf("\nProduct of the matrices:\n");
    for (i = 0; i < M; i++) 
        for (j = 0; j < M; j++)
            printf("%d\t", temp[i][j]);

        printf("\n");
    

    return 0;

非常感谢

答案

要消除将temp1复制到temp的循环,可以使用memcpy()

数组像这样连续地存储在内存中

+---------+---------+-----+---------+-----+---------+
| R[0][0] | R[0][1] | ... | R[1][0] | ... | R[4][4] |
+---------+---------+-----+---------+-----+---------+

因此,您只需简单地复制存储区

memcpy(temp, temp1, sizeof(temp1));

以上是关于我如何使用指针摆脱复制矩阵值的四个循环?的主要内容,如果未能解决你的问题,请参考以下文章

如何将数组矩阵的结果存储到较小的数组c#

模板表达式如何摆脱临时变量

如何找到矩阵中最小值的确切数量? [复制]

matlab矩阵里有很多有相同值的元素,如何剔除多余的,每个值只留一个元素

如何用chkconfig查看手动输入,跳出循环的四个命令

我应该如何摆脱循环? [关闭]