2013-09-21 179 views
1

我想爲大小爲「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; 
} 
+2

調試器只是不知道數組中有多少個元素。 C語言並沒有給它一個機會,一個數組沒有一個成員說它有多長。 C++語言確實如此,您只需使用* vector *。 –

回答

7

這是正常現象。 該變量是指向第一個元素的指針。 IDE並不真正知道它是一個數組。

把一個手錶指向變量,並告訴IDE你想看到更多的附加數字,像這樣。

Money, 5 

這應該向您展示分配的前5個元素。

怎麼樣? 我必須從記憶中做到這一點。

在調試菜單下有各種窗口可以打開。 那裏應該有一個或多個觀察窗口。 打開其中一個。

轉到您的源代碼中的變量,並通過雙擊它來選擇變量名稱。 將其拖入觀察窗並放開。

然後點擊觀察窗口中的變量。 編輯該值,在其後放置一個逗號5。 按回車。

應該做的伎倆。

+0

謝謝。你能不能請告訴我該怎麼做? (添加觀察點並告訴IDE我想看更多) –