将双指针分配给矩阵

发布于 2024-11-30 17:06:44 字数 494 浏览 0 评论 0原文

你好,我必须将一个矩阵分配给一个双指针,我编写了这段代码来简化事情。

int main (int argc, const char * argv[]) 
{

int ** matrix;
//// initialize the matrix 
matrix = malloc(sizeof(int *)*3);

for (int i=0; i<3; i++)
{

    matrix[i] = malloc(sizeof(int)*3);

}

// initialize the 2-d array
int matrixx[][3] = { {1,3,4},{5,3,1},{24,5,1} };

for (int i=0; i<3; i++) {
    ///good kind of assignment 
    matrix[i] = &matrixx[i];
}

/// error how i fix it ?
matrix = &matrixx[0][0];
}

hello i have to assign a matrix to a double pointer i wrote this code for simplify the things.

int main (int argc, const char * argv[]) 
{

int ** matrix;
//// initialize the matrix 
matrix = malloc(sizeof(int *)*3);

for (int i=0; i<3; i++)
{

    matrix[i] = malloc(sizeof(int)*3);

}

// initialize the 2-d array
int matrixx[][3] = { {1,3,4},{5,3,1},{24,5,1} };

for (int i=0; i<3; i++) {
    ///good kind of assignment 
    matrix[i] = &matrixx[i];
}

/// error how i fix it ?
matrix = &matrixx[0][0];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凹づ凸ル 2024-12-07 17:06:44

你无法修复它。 矩阵的类型是int **&matrixx[0][0]的类型为int *。这些是不兼容的。

如果您想维护指针数组机制,您的“良好分配”是正确的方法。但是,您的语法略有错误;它应该是:

for (int i=0; i<3; i++) {
    ///good kind of assignment 
    matrix[i] = matrixx[i];
}

另外,您不需要执行此操作的循环:(

for (int i=0; i<3; i++)
{
    matrix[i] = malloc(sizeof(int)*3);
}

一旦您重新分配这些指针,您就会导致内存泄漏,正如 @Chris 在下面指出的那样。)当然,除非您的意图是复制矩阵的内容。在这种情况下,你的做法肯定是错误的。

[另请注意,您没有在任何地方调用 free(),这意味着存在内存泄漏。]

You can't fix it. The type of matrix is int **. The type of &matrixx[0][0] is int *. These are incompatible.

Your "good kind of assignment" is the correct approach if you want to maintain the array-of-pointers mechanism. However, you have the syntax for it slightly wrong; it should be:

for (int i=0; i<3; i++) {
    ///good kind of assignment 
    matrix[i] = matrixx[i];
}

Also, you don't need the loop that does this:

for (int i=0; i<3; i++)
{
    matrix[i] = malloc(sizeof(int)*3);
}

(You'll incur a memory leak as @Chris points out below as soon as you re-assign these pointers.) Unless, of course, your intention is to copy the contents of the matrix. In which case, your approach is definitely wrong.

[Note also that you're not calling free() anywhere, which means you have a memory leak.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文