When and why do we use *?

May someone explain to me the reasons why we “dereference %s” or strings, within a PrintLine?
I don’t understand why we need this or when I need to be using it.
e.g. *
so: …%s), *Index);

This is the google results:
“Dereference a pointer is used because of the following reasons: It can be used to access or manipulate the data stored at the memory location, which is pointed by the pointer . Any operation applied to the dereferenced pointer will directly affect the value of the variable that it points to.”

But I don’t understand:
1: Where this information is stored from, and why its there or how I am to know how to use it (on my own)
2: What is a pointer?
Is this the line the code is from? e.g line 5?

Thanks for your time.

Also, why does our code, not print out the individual letters within our TArray?
Is that the use of %s?

for (int32 Index = 0; Index < 5; Index++)

    {

        PrintLine(TEXT("%s"), *Words[Index]);

    }

So: Words[1]
Would reference this 1st word in the TArray and not the first letter only?
I am confused on this. Sorry and thank you.

The formatting overload for PrintLine (the one taking more than 1 argument) uses FString::Printf which uses one of the printf family of functions from the C standard library. It being C, it can only format built-in types which FString is not.

The way C deals with strings is by having a null terminated sequence of characters. That is an array of char’s ending with the null character'\0'. So C API’s wanting to take a string just take a pointer to char and will keep reading bytes until it reaches that null character.

FString has overloded the * operator to return a pointer to the first character that it’s storing in its internal TArray<TCHAR> member. e.g.

const TCHAR* FString::operator*() const
{
    return Data.Num() ? Data.GetData() : TEXT("");
}

Where Data is the aforementioned array and GetData() returns a pointer to the first element. That code reads, if Data isn’t empty return a pointer to the first element else return an empty string literal.


Because you’re feeding it strings. To print out individual characters you would have to loop an additional time

for (int32 Index = 0; Index < 5; Index++)
{
    FString Word = Words[Index];
    for (int32 LetterIndex = 0; LetterIndex < Word.Len(); ++LetterIndex)
    {
        PrintLine(TEXT("%c, "), Word[LetterIndex]);
    }
}

P.S. you can create a code block by wrapping the code in three backticks

```
like this
```

1 Like

Thank you for the reply. A lot of this is going straight over my head. I did have some take away’s though. Thank you.

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms