You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从指针函数将矩阵数组返回至main函数?解决返回数组时的两类报错问题

Fixing Your Matrix Multiplication & Array Return Issues

Hey there! Let's walk through the problems in your code and get that matrix multiplication working correctly. You're hitting two common C pitfalls here—let's break them down:

First: The error: assignment to expression with array type & Invalid Pointer Access

Looking at your main function, you declared a as an int*, but then tried to use it like a 2D array with a[i][j]. That won't work because int* points to a single integer, not an array of integers (which is required for 2D array access). Also, your pointer function is declared to return an int, but you're returning a pointer—this type mismatch creates hidden issues too.

Second: The Core Dump (timeout: the monitored command dumped core)

Your pointer function creates a local 2D array ar[3][3] on the stack. When the function finishes executing, all local stack variables get cleaned up (their memory is released). Returning a pointer to this array gives you a "dangling pointer"—accessing this pointer in main is undefined behavior, which leads to the core dump.


How to Properly Pass/Return Arrays in C

C doesn't let you return arrays directly, but here are the safest ways to handle this (we'll use the first approach for your code, since it's the most straightforward and avoids memory leaks):

Approach 1: Pass the Result Array to the Function

Instead of trying to return an array from the function, create the result array in main and pass a pointer to it to your multiplication function. The function will then fill this array directly.

Fixed Code

/* multiplication of matrix in function and printing it in main */
#include <stdio.h>

// Function takes pointers to the two input matrices and the result matrix
void multiply_matrices(int *mat1, int *mat2, int *result) {
    int i, j, k;
    // Clear result matrix first (optional but safe)
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            *(result + i*3 + j) = 0;
        }
    }
    // Matrix multiplication logic (fixed index calculations)
    for (i = 0; i < 3; i++) {          // Rows of result
        for (j = 0; j < 3; j++) {      // Columns of result
            for (k = 0; k < 3; k++) {  // Sum over common dimension
                *(result + i*3 + j) += *(mat1 + i*3 + k) * *(mat2 + k*3 + j);
            }
        }
    }
}

int main() {
    int i, j;
    int ar[3][3] = { {1, 1, 3}, {2, 1, 8}, {3, 8, 1} };
    int ar1[3][3] = { {1, 1, 3}, {2, 1, 8}, {3, 8, 1} };
    int result[3][3];  // Result array created in main

    // Pass pointers to the matrices (decay to int*)
    multiply_matrices(&ar[0][0], &ar1[0][0], &result[0][0]);

    // Print the result
    printf("Result of matrix multiplication:\n");
    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Key Changes Explained:

  • Function Return Type: Changed to void since we don't need to return anything—we're modifying the result array directly.
  • Pass Result Array: We pass the result array from main to the function, so the memory stays valid for the entire life of main.
  • Fixed Index Calculation: Corrected the matrix multiplication indices to properly compute row * column products (your original index logic was off, which would have given wrong results even without the crashes).
  • Proper Array Access: In main, we use the 2D array directly (result[i][j]) since it's a properly declared 2D array.

Alternative Approach: Dynamic Allocation (If You Need to "Return" an Array)

If you really need the function to allocate and return the array (e.g., matrix size isn't known at compile time), you can use malloc to allocate memory on the heap (which doesn't get cleaned up when the function returns). Just remember to free the memory later to avoid leaks:

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

int** multiply_matrices_dynamic(int (*mat1)[3], int (*mat2)[3]) {
    // Allocate memory for 3 rows of int*
    int** result = malloc(3 * sizeof(int*));
    for (int i = 0; i < 3; i++) {
        // Allocate memory for each row (3 integers)
        result[i] = malloc(3 * sizeof(int));
        for (int j = 0; j < 3; j++) {
            result[i][j] = 0;
            for (int k = 0; k < 3; k++) {
                result[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
    return result;
}

int main() {
    int ar[3][3] = { {1, 1, 3}, {2, 1, 8}, {3, 8, 1} };
    int ar1[3][3] = { {1, 1, 3}, {2, 1, 8}, {3, 8, 1} };
    int** result = multiply_matrices_dynamic(ar, ar1);

    printf("Dynamic Result:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
        free(result[i]);  // Free each row
    }
    free(result);  // Free the row pointers

    return 0;
}

内容的提问来源于stack exchange,提问作者Sandesh Waghe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:12:36