Please help with a problem displaying a string using pointers

  • Thread starter Thread starter yungman
  • Start date Start date
  • Tags Tags
    Pointers String
Click For Summary
The discussion revolves around a programming issue related to copying a C-string into dynamic memory using pointers in C++. The user is experiencing problems with displaying the copied string, as it outputs garbage characters after the intended string. The primary focus is on the function `strCopy`, where the user mistakenly adds a null terminator to the wrong pointer. Instead of terminating the newly allocated memory (`Ar`), the code incorrectly attempts to terminate the original pointer (`*pptc`), leading to undefined behavior when displaying the string later. The solution involves correcting the line that adds the null terminator to ensure it is applied to the correct memory location. Additionally, the importance of manually tracing through the code to identify such errors is emphasized as a valuable debugging practice.
yungman
Messages
5,741
Reaction score
294
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.
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";
}
Compile error Listing 7.2.jpg


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
 
Technology news on Phys.org
yungman said:
I think I did it right, but I cannot display without garbage at the end of the string.

Then you didn't do it right, did you?

You have asked us several hundred questions on coding. You are asking us to do a lot of work on your behalf. A LOT of work. You have to hold up your end of the implicit bargain and put in some effort yourself.

Walk through your code by hand/on-paper/not using a computer using a small test string - e.g. "AB\0". Your error should be immediately apparent.
 
  • Like
Likes sysprog and Ranvaldo
yungman said:
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.
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";
}
View attachment 268837

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
just a suggestion you first take a sentence as input and then find its length instead of giving length directly.after input you can initialize the array with length.
see if it helps.
 
Vanadium 50 said:
Then you didn't do it right, did you?

You have asked us several hundred questions on coding. You are asking us to do a lot of work on your behalf. A LOT of work. You have to hold up your end of the implicit bargain and put in some effort yourself.

Walk through your code by hand/on-paper/not using a computer using a small test string - e.g. "AB\0". Your error should be immediately apparent.

I actually spent a few hours going back and fore looking at the program and test before I posted late last night. I looked at it again today, I still cannot see why it's different.

As I said, I display the array in line 36, it is CORRECT, exactly what it is expected. But in line 41, the while loop cannot detect the '\0' until much later, thereby spitting out garbage.

Today, I even display the content of array pointed by pptc right when entering the function to make sure I have the '\0' at the end of the string and display line by line. It is correct. Meaning I passed the pointer correctly, display the array pointed to correctly.

As you see, the string "This is a test" was copied from *(Ar + index) = *(*pptc + index) correctly, just somehow after getting out of the while loop, the '\0' cannot be detected in line 41.

I am at a lost on this. Like I said, I spent hours on this exhausted everything I can think of before I posted. I really appreciate all the help here, I learn to work on it for hours, look on line before I post to ask questions. This is just one I cannot figure out. Here is the function strCopy I modified:
C++:
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 << " Before *ppt copy to Ar: ";
    while (*(*pptc + count) != '\0')
    {
        cout << *(*pptc + count) << " count = " << count << "\n\n";
        count++;
    }
    cout << "\n\n After *pptc copy to Ar: ";
    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: ";
    count = 0;
    while (*(*pptc + count) != '\0')
    {
        cout << *(*pptc + count) << " count = " << count << "\n\n";
        count++;
    }
    cout << "\n\n";
}

You can see in line 7 right after entering into the function, I display the string pointed by *pptc, it is correct with '\0' at the end and it display " This is a test". this proofed I pass the array pointed by *pptc correctly.

The line I use to display the string is while (*(*pptc + count) != '\0')
It's the same test condition. There should NOT be any difference in displaying. Something changed between line 36 and 41. I just cannot see why.
 
Last edited:
Vanadium 50 said:
Walk through your code by hand/on-paper/not using a computer using a small test string - e.g. "AB\0". Your error should be immediately apparent.

You decided not to do this, and instead do something else. It didn't work. So you came back to ask your question again.

The answer is the same:

Walk through your code by hand/on-paper/not using a computer using a small test string - e.g. "AB\0". Your error should be immediately apparent.

I'd make the above text blinking if I could. This will not only help you debug this piece of code but help you debug code in the future.
 
I found it, it's not even in the way I did it. It's line 41 *(*pptc + index) = '\0'; to put the NULL after the last character. it should be *(Ar+ index) = '\0'; as it's the one that will be sent back. It's is just a simple line to add a terminator to the c-string and I put it in the wrong string.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
4
Views
2K
  • · Replies 23 ·
Replies
23
Views
2K
  • · Replies 32 ·
2
Replies
32
Views
3K
  • · Replies 13 ·
Replies
13
Views
3K
Replies
12
Views
2K
Replies
10
Views
2K
Replies
20
Views
2K
  • · Replies 118 ·
4
Replies
118
Views
9K
  • · Replies 66 ·
3
Replies
66
Views
6K
Replies
89
Views
6K