【发布时间】:2016-08-29 16:37:00
【问题描述】:
问题如下:
我创建了一个动态矩阵,使用指针matrix1
我想将此矩阵的副本创建到另一个,matrix2
我想这样做,这样我就可以与matrix2 混淆,而不会与matrix1 混淆
所以我尝试执行以下操作:
int main()
{
int **matrix1, **matrix2, size1 = 10, size2 = 2;
matrix1 = create_matrix(size1, size2);
//I want to copy the value of matrix1 into matrixq2 and NOT the index
**matrix2 = **matrix1
}
但是程序中断并显示以下内容:
我知道,从外观上看,将函数 create_matrix 使用两次会更容易,matrix1 和另一个 matrix2。但是在我原来的程序中,这将是太多的工作,因为我做了很多事情来完成矩阵。
哦,顺便说一句,我想避免使用 C++,有没有办法在不使用它的情况下做到这一点?对我来说会更好。
“create_matrix”代码如下:
//The program will read a file with the name of endereco, and create a matrix contPx3 out of it
int ** cria_matrix(char endereco[], int contP)
{
FILE *fPointer;
int i, contE, auxIndex, auxNum, **processos, cont_line = 0;
char line[100];
bool flag = true, flag2;
fPointer = fopen(endereco, "r");
//Here the creation of the matrix
processos = (int**)malloc(sizeof(int*) * contP);
for (i = 0; i < contP; i++)
processos[i] = malloc(sizeof(int) * 3);
//For now and on, is the rules of how the data will be placed on the matrix
contP = 0;
while (!feof(fPointer) && flag)
{
memset(&line[0], 'Ì', sizeof(line));
fgets(line, 100 , fPointer);
//Bassicaly is that in each line there will be 3 numbers only, diveded but as many spaces you want. The numbeer will be placed on the matrix on the determined line they are.
auxIndex = 0;
flag2 = false;
if(line[0] != '#')
for (i = 0; i < 100; i++)
{
if (line[i] != ' ' && line[i] != '\n' && line[i] != '\0' && line[i] != 'Ì')//&& line[i] != 'à'
{
auxNum = line[i] - '0';
processos[contP][auxIndex] = auxNum;
auxIndex++;
flag2 = true;
}
}
if (flag2)
contP++;
cont_line++;
if (auxIndex != 3 && auxIndex != 0)
{
flag = false;
printf("ERRO na linha: %d No processo: %d\nProvavelmente mais ou menos que 3 numeros separado por espacos\n", cont_line, contP);
}
}
fclose(fPointer);
if (!flag)
system("PAUSE");
return processos;
}
【问题讨论】:
-
你没有发布完整的代码。
-
@parik,这不是一个有效的副本。那里的数据类型是
T[N][M],而这里是T**。从那里盲目地应用解决方案可能会使 OPs 程序崩溃。 -
另外,复制第一级间接,而不是第一个元素:
memcpy(*matrix2, *matrix1, size1 * size2 * sizeof(int))。如果你定义正确,**matrix1应该是int。 -
最后还是需要分配实际的
matrix2。目前,它指向垃圾箱。
标签: c matrix pointer-to-pointer cop