The code does print out. But it's giving that error. The objective is to print it out as an example: 4 as: aaaa 8 as: aaaaaaaa 12 as: aaaaaaaaaaaa 16 as: aaaaaaaaaaaaaaaa
#include<iostream>
using namespace std;
int current_size = 4;
int resize_step = 4;
void add_number(char* &arr, int count, char x){
if(count == current_size){
current_size += resize_step;
char* newArr = new char[current_size];
for(int i=0;i<count;i++) newArr[i] = arr[i];
delete arr;
arr = newArr;
}
arr[count-1] = x;
}
//After
int main(){
char* arr = new char[current_size];
for(int count=0;count<4;count++){
add_number(arr, count+1, '1' + count);
}
for(int i=0;i<4;i++) cout<<arr[i]<<" ";
return 0;
}
So I have rewritten the code. but the expected output is: Expected answer: 4 as: aaaa 8 as: aaaaaaaa 12 as: aaaaaaaaaaaa 16 as: aaaaaaaaaaaaaaaa
I am only getting the first line 4 as aaaa
#include <iostream>
using namespace std;
int current_size = 4;
int resize_step = 4;
//This functions add the value x at the last position in the array
//The count of elements is indicated by the variable count
//If the array is already at maximum it resizes
//The array starts at current_size size and resizes in resize_step intervals
void add_number(char*& arr, int count, char x)
{
//Your code starts here
arr = new char[current_size];
for (int i = 0; i < current_size; i++)
{
//arr[i] = x;
if (count >= current_size)
{
current_size += resize_step;
char* array2 = new char[current_size - resize_step];
for (int j = 0; j < sizeof(array2); j++)
{
array2[j] = arr[j];
}
delete[](arr);
arr = array2;
}
arr[i] = x;
}
}
int main() {
char* arr = new char[current_size];
char x = 'a';
int element = 8;
add_number(arr, element, x);
for (int i = 0; i < current_size; i++)
{
cout << arr[i];
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.