奇怪!数组下标可以为负值?!
今天遇到了一个非常奇怪的现象!数组的下标可以负值!!搞不清怎么会是,烦请高手指点迷津!
#include "stdafx.h"#include <iostream>#include <fstream>#include <climits>#include <memory>#include <new>#define maxRow 5000#define maxCol 5000using namespace std;static int myReadData(double inData[], int nrow ,int ncol ,char Filedir[] );int _tmain(int argc, _TCHAR* argv[]){ int nrow,ncol,nmax,ttotalmax,nmin,ttotalmin; char myFiledir[255]; int *maxindex = new int [maxRow*maxCol]; int *minindex = new int [maxRow*maxCol]; double *inData = new double [maxRow*maxCol]; cout << "请分别输入数据矩阵的行数和列数:" ; cin >> nrow; cin >> ncol; myReadData(inData,nrow,ncol,myFiledir); //读取数据 return 0; //在这里设置断点,当程序运行到这里时,在监视窗口输入inData[-1],居然没有报错,而且显示了一个随机值!}static int myReadData(double *data,int nrow,int ncol,char Filedir[]) //读取数据,存在一个二维数据中{ fstream openfile; int i,j; openfile.open("E:/data.txt",ios::in); if(!openfile) { cout<<"文件打开失败!"<<endl; return 0 ; } for(i=0;i<nrow*ncol;i++) openfile >> data[i]; openfile.close(); return 1;}#include <stdio.h>#include <stdlib.h>void main(){ int a[8] = {0,1,2,3,4,5,6,7}; int *p = a + 2; //p指向a[2]的地址 printf("%d",p[-1]);//输出是1 system("pause");}
[解决办法]
监视窗口允许的,编译器不允许就可以了^_^。inData[-1]只是返回了inData前面系统隐藏的cookies,并以double解析而已。
不同的分配方式,系统有着不同的cookies
------解决方案--------------------