看看這個代碼:C++可變參數的參數問題
的StdAfx.h:
#pragma once
#include <stdarg.h>
template<class T>
class DArray {
private:
T* elements;
int dimensions, length;
int* lengths;
public:
DArray() {
dimensions = 0;
length = 0;
}
DArray(int dims, ...) {
va_list args;
va_start(args, dims);
dimensions = dims;
lengths = new int[dims];
length = 1;
for (int i = 0; i < dims; i++) {
lengths[i] = va_arg(args, int);
length *= lengths[i];
}
va_end(args);
elements = new T[length];
}
T get(...) {
va_list args;
va_start(args, dimensions);
int weight = 1;
int index = va_arg(args, int);
for (int i = 1; i < dimensions; i++) {
weight *= lengths[i - 1];
index += va_arg(args, int) * weight;
}
va_end(args);
return elements[index];
}
void set(T value, ...) {
va_list args;
va_start(args, dimensions);
int weight = 1;
int index = va_arg(args, int);
for (int i = 1; i < dimensions; i++) {
weight *= lengths[i - 1];
index += va_arg(args, int) * weight;
}
va_end(args);
elements[index] = value;
}
~DArray() {
if (lengths != nullptr)
delete[] lengths;
//thanks to an answer pointing out I forgot to add this part:
if (elements != nullptr)
delete[] elements;
}
};
Main.cpp的:
#include "stdafx.h"
#include <iostream>
DArray<int> generateRandomMatrix(int columns, int rows) {
int x, y;
DArray<int> matrix = DArray<int>(2, columns, rows);
for (y = 0; y < rows; y++) {
for (x = 0; x < columns; x++)
matrix.set(rand(), x, y);
}
return matrix;
}
int main() {
int x, y;
DArray<int> matrix;
do {
matrix = generateRandomMatrix(10, 5);
for (y = 0; y < 5; y++) {
for (x = 0; x < 10; x++)
printf("%d", matrix.get(x, y));
}
printf("\n\nPress Enter to restart...\n");
getchar();
} while (true);
return 0;
}
出於某種原因,這對我的生活我不明白,當從generateRandomMatrix()內調用matrix.set()時,索引變量的負值爲-462266869,這導致索引超出界限異常。
如果只有正參數傳遞給函數,index如何爲負?
(這裏是局部變量的截圖看,窗口,它的價值:http://i.imgur.com/LfGQ8OF.png)
通常這意味着溢出。 – AndyG
我無法理解如何從兩個簡單的單位數整數參數發生溢出:/ –
您沒有遵循三/五規則,這是值得的。 – chris