我想爲大小爲「n」的int數組分配內存。我已經使用如何在Visual Studio 2012中動態分配內存Visual C++
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;
}
調試器只是不知道數組中有多少個元素。 C語言並沒有給它一個機會,一個數組沒有一個成員說它有多長。 C++語言確實如此,您只需使用* vector *。 –