본문 바로가기

Programming/C++ 1

[C++] ReverseString

반응형

Working

#include<iostream>
using namespace std;

char* revstr_dm(char* src, int len);

int main__()
{
	char orig[] = "ABCD";
	cout << "orig : " << orig << endl;
	cout << (void*)orig << endl;
	cout << (void*)&orig[0] << endl;
	cout << (void*)&orig[1] << endl;

	int len = strlen(orig);

	cout << sizeof(orig) << endl; //5
	cout << strlen(orig) << endl;//4
	char* copy = revstr_arr(orig, len)
	int len = strlen(orig);
	char* copy = revstr_dm(orig, len); //array를 매개변수로 보내려면 매개변수로 길이를 보내야한다.
	//2. Use
	cout << copy << endl;
	delete[] copy; copy = NULL; //3. Free the memory

	return 0;
}

char* revstr_dm(char* src, int len)
{
	//1. Alocate Dynamic Memory
	char* reverse = new char[len + 1];
	//Reverse String using src put null char at the end
	for (int i=0; i<len;i++)
	{
		reverse[i] = src[len - i - 1];
	}
	reverse[len] = NULL; // '\0';
	//Return starting address of the dynamic memory
	return reverse;

}

 

Not working

#include<iostream>
using namespace std;

char* revstr_dm(char* src, int len);
char* revstr_arr(char* src, int len);


int main()
{//not working
	char orig[] = "ABCD";
	cout << "orig : " << orig << endl;
	cout << (void*)orig << endl;
	cout << (void*)&orig[0] << endl;
	cout << (void*)&orig[1] << endl;

	int len = strlen(orig);

	cout << sizeof(orig) << endl; //5
	cout << strlen(orig) << endl;//4
	char* copy = revstr_arr(orig, len);
	int len = strlen(orig);
	//char* copy = revstr_dm(orig, len); //array를 매개변수로 보내려면 매개변수로 길이를 보내야한다.
	//2. Use
	cout << copy << endl;
	//delete[] copy; copy = NULL; //3. Free the memory

	return 0;
}
char* revstr_arr(char* src, int len)
{
	char reverse[10];
	for (int i = 0; i < len; i++)
	{
		reverse[i] = src[len - i - 1];
	}

	reverse[len] = NULL;
	return reverse;
}

char* revstr_dm(char* src, int len)
{
	//1. Alocate Dynamic Memory
	char* reverse = new char[len + 1];
	//Reverse String using src put null char at the end
	for (int i = 0; i < len; i++)
	{
		reverse[i] = src[len - i - 1];
	}
	reverse[len] = NULL; // '\0';
	//Return starting address of the dynamic memory
	return reverse;

}

-> no delete / objects, object array problem

반응형

'Programming > C++ 1' 카테고리의 다른 글

[C++] ShiftString  (0) 2021.04.07
[C++] Chapter 11. Pointers and Dynamic Memory Management  (0) 2021.04.04
[C++] Swap Function  (0) 2021.04.04
[C++] Chapater 7. Single-Dimensional Arrays and C-Strings  (0) 2021.04.04
[C++] Chapter 6. Functions  (0) 2021.04.04