Ama*_*ngh 1 c++ arrays memory-management visual-studio-2012
我想为大小为"n"的int数组分配内存.我用过
int *Money = new int[n];
Run Code Online (Sandbox Code Playgroud)
并且
int *Money = (int*) malloc(n*sizeof(int))
Run Code Online (Sandbox Code Playgroud)
但都没有奏效.在程序期间,我从文件"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;
}
Run Code Online (Sandbox Code Playgroud)
这个是正常的.变量是指向第一个元素的指针.IDE并不真正知道它是一个数组.
在变量上加上一个观察点,并通过向它添加一个数字告诉IDE你想看到更多.
Money, 5
Run Code Online (Sandbox Code Playgroud)
那应该向你展示分配的前5个要素.
怎么样?我必须从记忆中做到这一点.
在调试菜单下,您可以打开各种窗口.应该有一个或多个手表窗.打开其中一个.
转到源代码中的变量,然后双击选择变量名称.将其拖入观察窗口然后放开.
然后单击监视窗口中的变量.编辑该值,在其后面加上逗号5.按回车键.
应该做的伎俩.