以下是我的代码。我正在尝试编写一个从用户获取字符串并将其存储在大小为10的字符数组中的程序。我想从左侧显示一个计数字母的子字符串,其中count由用户给出并打印如果用户按计数输入超出范围的字符串,则为适当的消息。
但我的代码抛出CRT内存分配错误,现在是“LNK1168”。enter image description here
我该如何解决这个问题?
#include<iostream>
#include<string>
using namespace std;
void Destructor(char *p)// function
{
int i = 0;
cout << "Showing the substring .. " << p << endl << endl;;
}
char* left(const char* target, const int count)
{
char* ptr = NULL;// initialization of pointer
ptr = new char[count];// allocating dynaic memory ..
cout << ptr << endl << endl;
if (count > 10)
{
cout << " Input is out of range " << endl;
}
else
{
for (int i = 0; i < count; i++)
{
ptr[i] = target[i];
cout << ptr[i] << endl;
if (i == count - 1)
{
ptr[i + 1] = '\0';
break;
}
}
cout << ptr << endl;
Destructor(ptr);//function call ....
}
return ptr;
}
void main()
{
const int SIZE = 10;
int count = 0;
char* ptr = NULL;
string userInput;
char arr[SIZE] = { '\0' };
ptr = arr;
cout << "Please Enter a string :-";
getline(cin, userInput);
for (int i = 0; i <SIZE; i++)
{
ptr[i] = userInput[i];
cout << "COUNT " << i << endl;
if (i == SIZE - 1)
{
ptr[i + 1] = '\0';
break;
}
if (userInput[i] == '\0')
break;
/*if (i == 9)
break;*/
}
cout << "Checking character array in main .. " << ptr << endl;
cout << "Enter a substring count : ";
cin >> count;
ptr = left(ptr, count);// function call...
delete ptr;//deleting new memory ...
}