我有以下代碼:(請原諒此代碼的長度)。我正試圖訪問矢量內的矢量元素。 table_info * get_table_info函數獲取特定表的table_info向量的值。當我嘗試檢查column_info向量的值時,遇到一個奇怪的錯誤,程序突然終止。在C++中使用向量內的矢量訪問元素時出現異常程序終止錯誤
typedef struct _column_info {
char name[20]; // columns name
int type; // 0:INT, 1: CHAR
int size;
int offset; // start position
} column_info;
typedef struct _table_info {
char name[20];
int column_count;
char columns[100];
vector <column_info> col; //col[0], col[1]...
char primary_key[5];
int recordsize;
int totalsize;
int records;
} table_info;
vector <table_info> v;
void create_table(char* tablename, struct columns *cc , int num_col, char* pkey) {
char* new_columns;
new_columns = (char*)malloc(256*sizeof(char));
strcpy(new_columns,"");
int len = 0;
len = num_col;
for (int i=0 ; i < len ; i++)
{
strcat(new_columns, cc[i].c_name);
strcat(new_columns, ":");
strcat(new_columns, cc[i].c_type);
if (strcmp(cc[i].c_type,"char") == 0)
{
strcat(new_columns, "(");
strcat(new_columns, cc[i].c_size);
strcat(new_columns, ")");
record_size = record_size + atoi(cc[i].c_size);
}
else
record_size = record_size + 4;
if(i != (len-1))
strcat(new_columns, ",");
}
table_info new_table;
strcpy(new_table.name, tablename);
strcpy(new_table.columns, new_columns);
strcpy(new_table.primary_key, pkey);
new_table.recordsize = record_size;
new_table.totalsize = 0;
new_table.records = 0;
v.push_back(new_table);
column_info cols;
int offset = 0;
for(int x=0;x<num_col;x++)
{
strcpy(cols.name, cc[x].c_name);
if (strcmp(cc[x].c_type,"char") == 0)
cols.type = 1;
else
cols.type = 0;
cols.size = atoi(cc[x].c_size);
cols.offset = offset;
offset += cols.size;
new_table.col.push_back(cols);
}
table_info* table_info;
table_info = get_table_info(tablename);
int offset2=0;
int size2 = 0;
for (int i = 0; i < num_col ; i++)
{
offset2 = table_info->col.at(i).offset; // ERROR: ABNORMAL PROGRAM TERMINATION
printf("offset:%d\n",offset2);
size2 = table_info->col.at(i).size;
}
}
table_info* get_table_info(const string& tablename)
{
printf("table info \n");
for (int i = 0; i < (int) v.size(); i++)
{
if (strcmp(v.at(i).name, tablename.c_str()) == 0)
return &v.at(i);
}
return NULL;
}
任何想法爲什麼這個程序終止?請幫忙。
我想這是在Windows?我認爲「異常程序終止」是一個未捕獲的異常,可能由'vector :: at'引發,因爲'i'超出範圍。無論如何,它可能很容易用調試器修復。 – netcoder 2012-03-30 15:38:49
是的,這是在Windows上,我確實嘗試使用Eclipse進行調試。但調試器突然停止在線。 num_col的值是可以的。我查過了,所以我不認爲這是因爲我的價值超出了界限。任何其他建議都會有幫助。 – PGOnTheGo 2012-03-30 15:54:03