我想为大小为“n”的 int 数组分配内存。我用过
int *Money = new int[n];
并且
int *Money = (int*) malloc(n*sizeof(int))
但都没有奏效。在程序期间,我从文件“Test.txt”中读取并填充数组。但是在调试时,我总是在 Money 数组中看到一个条目(第一个),它的大小是 1。这里的其他动态分配的数组也是如此。
我怎样才能让它工作?
#include<cstdio>
#include<cstdlib>
#include<assert.h>
int *Money;
int *Earn;
int *Sorted;
int *R1;
int *R2;
bool *Visited;
int visited;
void TSort(int room, int n);
int main(){
FILE *in=fopen("Test.txt","r");
int n,ind=0,money,r1=0,r2=0;
char room1[7], room2[7];
fscanf(in,"%d",&n);
printf("%d\n",n);
Money = (int*) malloc((n+1)*sizeof(int));
Sorted = (int*) malloc((n+1)*sizeof(int));
Sorted[n] = n;
R1 = (int*) malloc(n*sizeof(int));
R2 = (int*) malloc(n*sizeof(int));
Visited = (bool*) malloc((n+1)*sizeof(bool));
Earn = (int*) malloc((n+1)*sizeof(int));
visited=0;
/* In this for loop I read in the input from the said file */
for(int i=0;i<n;i++){
fscanf(in,"%d %s %s",&money, room1, room2);
Money[i]=money;
Earn[i] = -1;
if(room1[0] == 'E')
R1[i] = n;
else{
int j=0;
r1=0;
while (room1[j]){
r1 = 10*r1 + (room1[j]-48);
j++;
}
R1[i] = r1;
}
if(room2[0] == 'E')
R2[i] = n;
else{
int j=0;
r2=0;
while (room2[j]){
r2 = 10*r2 + (room2[j]-48);
j++;
}
R2[i] = r2;
}
Visited[i]=false;
}
/* Reading and initializations end */
Earn[0] = Money[0];
TSort(0,n);
for(int i=0; i<n; i++){
assert(Earn[Sorted[i]] != -1);
int curr=Sorted[i];
int r1 = R1[curr];
int r2 = R2[curr];
int possible = Earn[curr] + Money[r1];
if(possible > Earn[r1]) Earn[r1] = possible;
possible = Earn[curr] + Money[r2];
if(possible > Earn[r2]) Earn[r2] = possible;
}
printf("%d\n",Earn[n]);
getchar();
return 0;
}
void TSort(int room, int n){
while(visited<n){
Visited[room] = true;
Sorted[visited] = room;
visited++;
if((R1[room] != n)&&(!Visited[R1[room]])) TSort(R1[room],n);
if(((R2[room] != n))&&(!Visited[R2[room]])) TSort(R2[room],n);
}
return;
}