모든 유형을 수용 할 수 있도록 포인터와 템플릿을 사용하여 C ++에서 동적 배열 구현을 만들려고합니다. 코드는 잘 작동 int
했지만 사용 string
하면 오류가 발생합니다. 나는 다른 SO 질문을 온라인으로 시도했지만 내 시나리오에 대해 아무것도 찾지 못했습니다.
암호:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
class dynamicIntArray
{
private:
T *arrPtr = new T[4]();
int filledIndex = -1;
int capacityIndex = 4;
public:
// Get the size of array
int size(void);
// Insert a data to array
bool insert(T n);
// Show the array
bool show(void);
};
template <typename T>
int dynamicIntArray<T>::size(void)
{
return capacityIndex + 1;
}
template <typename T>
bool dynamicIntArray<T>::insert(T n)
{
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
return true;
}
else if (filledIndex == capacityIndex)
{
// Create new array of double size
capacityIndex *= 2;
T *newarrPtr = new T[capacityIndex]();
// Copy old array
for (int i = 0; i < capacityIndex; i++)
{
newarrPtr[i] = arrPtr[i];
}
// Add new data
newarrPtr[++filledIndex] = n;
arrPtr = newarrPtr;
return true;
}
else
{
cout << "ERROR";
}
return false;
}
template <typename T>
bool dynamicIntArray<T>::show(void)
{
cout << "Array elements are: ";
for (int i = 0; i <= filledIndex; i++)
{
cout << arrPtr[i] << " ";
}
cout << endl;
return true;
}
int main()
{
dynamicIntArray<string> myarray;
myarray.insert("A");
myarray.insert("Z");
myarray.insert("F");
myarray.insert("B");
myarray.insert("K");
myarray.insert("C");
cout << "Size of my array is: " << myarray.size() << endl;
myarray.show();
}
오류:
segmentaion fault (core dumped)
클래식 오프 바이 원 오류 :
if (filledIndex < capacityIndex)
{
arrPtr[++filledIndex] = n;
삽입하기 전에 5 번째 항목 filledIndex
인 3
< 4
( capacityIndex
). 이로 인해 arrPtr[4]
액세스 할 수 있습니다 (범위가 현재 [0..3]이므로 범위를 벗어난 액세스).
처음에 설정하여 수정 filledIndex
에 0
변화 arrPtr[++filledIndex] = n;
에arrPtr[filledIndex++] = n;
하지만 코드에는 메모리 누수, 의심스러운 이름 및 스타일 등 심각한 결함이 있습니다 . 수정 된 버전을 https://codereview.stackexchange.com/에 게시하는 것이 좋습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다