将双指针分配给矩阵
你好,我必须将一个矩阵分配给一个双指针,我编写了这段代码来简化事情。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你无法修复它。
矩阵
的类型是int **
。&matrixx[0][0]
的类型为int *
。这些是不兼容的。如果您想维护指针数组机制,您的“良好分配”是正确的方法。但是,您的语法略有错误;它应该是:
另外,您不需要执行此操作的循环:(
一旦您重新分配这些指针,您就会导致内存泄漏,正如 @Chris 在下面指出的那样。)当然,除非您的意图是复制矩阵的内容。在这种情况下,你的做法肯定是错误的。
[另请注意,您没有在任何地方调用
free()
,这意味着存在内存泄漏。]You can't fix it. The type of
matrix
isint **
. The type of&matrixx[0][0]
isint *
. 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:
Also, you don't need the loop that does this:
(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.]