获取垃圾值,而在C印花矩阵 [英] Getting a garbage value while printing matrix in C

查看:104
本文介绍了获取垃圾值,而在C印花矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学会了C语言编程三年前和现在,当我的Java和C#的经验以后重新审视它,我现在面临的指针的一些问题。所以我试图写一个简单的矩阵加法程序,但我不知道为什么我得到一些奇怪的值,同时打印矩阵。

I learned C programming language three years back and now when i am revisiting it after the experience of java and c# i'm facing some issues with pointers. So i tried to write a simple matrix addition program but i don't know why i'm getting some strange values while printing the matrices.

code:

#include <stdio.h>

int* sumOfMat(int* m1,int* m2)
{
    printf("Matrix A: \n");
    printMat(m1);
    printf("Matrix B: \n");
    printMat(m2);
    int mat3[3][3];
    int row=0,col=0,k=0,sum=0;
    for(;row<3;row++)
    {
        col=0;
        for (;col<3 ;col++ )
        {
            sum=(*m1+*m2);
            m1++;
            m2++;
            mat3[row][col]=sum;
        }
    }

    printf("Result: \n");
//    printMat(mat3);  //this statement is giving me a correct output.
    return mat3;
}

void printMat(const int m[3][3])
{
    int row,col;
    for (row=0;row<3 ;row++ )
    {
        for (col=0;col<3 ;col++ )
        {
            printf("%d\t",m[row][col]);
        }
        printf("\n");
    }

}


int main(void) {
int mat1[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int mat2[3][3]={{1,2,3},{4,5,6},{7,8,9}};
//add
printf("Sum of the metrices : \n");
int* x=sumOfMat(&mat1,&mat2);
printMat(x);   // this call is providing me some garbage values at some locations.
return 0;
}

输出:

Success  time: 0 memory: 2292 signal:0
Sum of the metrices : 
Matrix A: 
1   2   3   
4   5   6   
7   8   9   
Matrix B: 
1   2   3   
4   5   6   
7   8   9   
Result: 
2   134514448   134514448   
8   10  12  
14  16  -1216458764 

演示

Demo

问:为什么我得到这个错误以及如何纠正它。

Question: Why i'm getting this error and how to correct it.

推荐答案

int mat3[3][3];

这是您的分配二维数组中的

allocates your 2d array on the stack

您正在返回一个指针数组。

You're returning a pointer to this array.

return mat3;

不幸的是,当函数调用结束堆栈展开和数组的内存不再出现,让你有一个指向垃圾。

Unfortunately when the function call ends the stack is unwound and the memory for the array is no longer there, so you have a pointer to garbage.

解决方案之一是将数组分配在函数并将其传递到 sumOfMat 作为参数。

One solution is to allocate the array in your main function and pass it into sumOfMat as a parameter.

这篇关于获取垃圾值,而在C印花矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆