首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C中制作返回2D整点的函数

如何在C中制作返回2D整点的函数
EN

Stack Overflow用户
提问于 2013-11-07 02:38:21
回答 2查看 111关注 0票数 0

我有一个关于返回整点2D的问题。假设我有一个整点2D,它代表2D矩阵。我想把矩阵转置一下。我已经成功运行,如果我使用正常的方式(返回int**),但问题是不能删除内存时,malloc。因此,我想使用引用函数将此函数转换为返回transposeMatrix(...)//它将返回矩阵G的转置

代码语言:javascript
复制
int** transposeMatrix(int** G,int  nRowSize,int nColumnSize)
{
    int **GT=NULL;
    int nRowIndex,nColumnIndex;
    GT= (int**)malloc(sizeof(int*) * nRowSize);
    memset(GT, 0, sizeof(int*) * nRowSize);
    for (nRowIndex = 0; nRowIndex < nRowSize; nRowIndex++)
        {
        GT[nRowIndex] = (int*)malloc(sizeof(int) * nColumnSize);
        for (nColumnIndex = 0; nColumnIndex < nColumnSize; nColumnIndex++)
            {
                       GT[nRowIndex][nColumnIndex]=G[nColumnIndex][nRowIndex];
            }
        }
     return  GT;
}

你能帮帮我吗?

EN

回答 2

Stack Overflow用户

发布于 2013-11-07 02:56:42

您可以将指针传递给G

代码语言:javascript
复制
void transposeMatrix(int*** PG,int  nRowSize,int nColumnSize)
}
  ...
  GT[nRowIndex][nColumnIndex]=(*PG)[nColumnIndex][nRowIndex];
  ...
  *GP = GT;
}

或者通过引用传递G (我不记得C是否允许这样做):

代码语言:javascript
复制
void transposeMatrix(int** &G,int  nRowSize,int nColumnSize)
}
  ...
  GT[nRowIndex][nColumnIndex]=G[nColumnIndex][nRowIndex];
  ...
  G = GT;
}
票数 0
EN

Stack Overflow用户

发布于 2013-11-07 19:47:02

好了,在对你的问题有了一些想法之后,因为我非常喜欢这个主题。我觉得我找到了一个合适的解决方案。转置函数接受矩阵M的改变,使得它指向转置后的矩阵的正确存储器地址。因此,它释放了先前的矩阵m,以解决任何内存问题并改变维度,以便在调用者中正确使用。

如果仍然缺少部件,请注解。

我希望这能帮到你。万事如意

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int **matrix;

matrix newMatrix(int row, int col)
{
    int idx;
    matrix m = malloc(row * sizeof(int*));
    for (idx = 0; idx < row; ++idx)
    {
        m[idx] = malloc(col * sizeof(int));
    }
    return m;
}

void freeMatrix(matrix m, int row, int col)
{
    int idx;
    for (idx = 0; idx < row; ++idx)
    {
        free(m[idx]);
    }
    free(m);
}

void printMatrix(matrix m, int row, int col)
{
    int r, c;
    for (r = 0; r < row; r++)
    {
        for (c = 0; c < col; c++)
        {
            printf("%d ", m[r][c]);
        }
        printf("\n");
    }
}

void swap(int *a, int *b)
{
    int h = *a;
    *a = *b;
    *b = h;
}

void transpose(matrix *m, int *row, int *col)
{
    int r, c;
    matrix t = newMatrix(*col, *row);

    for (r = 0; r < *row; ++r)
    {
        for (c = 0; c < *col; ++c)
        {
            t[c][r] = (*m)[r][c];
        }
    }
    freeMatrix(*m, *row, *col);
    swap(row, col); 
    (*m) = t;
}

int main()
{
    int row = 2, col = 3;
    matrix m = newMatrix(row, col);

    m[0][0] = 1;
    m[0][1] = 1;
    m[0][2] = 1;
    m[1][0] = 2;
    m[1][1] = 4;
    m[1][2] = 3;

    printMatrix(m, row, col);
    transpose(&m, &row, &col);
    printMatrix(m, row, col);       

    return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19820077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档