- #1
yungman
- 5,755
- 293
Hi
I wrote a program to copy an array of C-String into dynamic memory in the function using pointers. I think I did it right, but I cannot display without garbage at the end of the string.
As shown, I display at line 36 and you can see it is correct, it jump out of the while loop after completing the whole sentence and it is correct, no garbage.
But when I display using while loop in line 41 using the same logic to stop when '\0' is encountered, I got garbage as shown after the "This is a test". the same issue happens when return back to the main.
I don't see anything wrong, please help,
thanks
I wrote a program to copy an array of C-String into dynamic memory in the function using pointers. I think I did it right, but I cannot display without garbage at the end of the string.
C++:
//10.9 function copy C-String using pointer
#include <iostream>
using namespace std;
void strCopy(char**, int );
int main()
{
int count = 0;
const int length = 30;
char first[length];
char* ptc;
ptc = first;//pointer ptc points to first[0]
cout << " Enter a sentence no more than " << (length - 1) << " characters: ";
cin.getline(first, length);
strCopy(&ptc, length); //passing the address of ptc and length
cout << " The string you entered is: ";
while (*(ptc + count) != '\0')
{
cout << *(ptc + count);
count++;
}
cout << "\n\n";
delete[] ptc;
return 0;
}
void strCopy(char **pptc, int size)//receive pointer to pointer pptc.
{
int count = 0;
char *Ar = new char[size];//pointer Ar pointing to start of memory
int index = 0;
cout << " After Ar copy to *ppt: ";
while (*(*pptc + index) != '\0')//pptc is pointer to pointer, *pptc is address of pointer.
{
*(Ar + index) = *(*pptc + index);
cout << *(*pptc + index);
index++;
}
cout << "\n\n";
*(*pptc + index) = '\0'; //adding a terminating character.
*pptc = Ar;
cout << " The string you entered is: ";
while (*(*pptc + count) != '\0')
{
cout << *(*pptc + count);
count++;
}
cout << "\n\n";
}
As shown, I display at line 36 and you can see it is correct, it jump out of the while loop after completing the whole sentence and it is correct, no garbage.
But when I display using while loop in line 41 using the same logic to stop when '\0' is encountered, I got garbage as shown after the "This is a test". the same issue happens when return back to the main.
I don't see anything wrong, please help,
thanks