-1

Pointers have always made me blank about the logic I intend to use in code, If someone can help me understand a few concepts that would be really helpful. Here's a code snippet from my program,

vector <char> st; 
char *formatForHtml(string str, string htmlTag)
{ 
    string strBegin;
    strBegin = "<";
    strBegin.append(htmlTag);
    strBegin.append(">");
    strBegin.append(str);
    string strEnd = "</";
    strEnd.append(htmlTag);
    strEnd.append(">");
    strBegin.append(strEnd);
    st.resize(strBegin.size());
    for (int i =0;i <strBegin.size();i++) {
        st[i] = strBegin.at(i);
    }
    return &st[0];
}

In the code above if I have to return address of st[0], I have to write the function of type char *. I need to know the reason to do so, also if address is the integer value why can I not define function as an int type?

P.S. It's a beginner level doubt.

vin
  • 869
  • 4
  • 17
  • 33

6 Answers6

1

You don't tell us what st is, so we can't tell whether the code is totally incorrect, or just bad design. If st is a typo for str (just guessing, since str isn't used anywhere), then you have undefined behavior, and the program is incorrect, since you're returning a pointer into an object which has been destructed. At any rate, a function like formatForHtml should return an std::string, as a value, and not a pointer (and certainly not a pointer to a non-const).

I might add that you don't use a loop to copy string values character by character. std::string acts as a normal value type, so you can just assign: st = strBegin;.

EDIT:

Just for the record, I've since reexamined your code. The natural way of writing it would be:

std::string
formatForHtml( std::string const& cdata, std::string const& tag )
{
    return '<' + tag + '>' + cdata + "</" + tag + '>';
}

No pointers (at least not visible---in fact, "+ operator), and full use of std::strings facilities.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0

I have to write the function of type 'char *' I need to know the reason to do so

There's no reason to do so. Just return a std::string.

From the looks of your code, st is a std::vector<char>. Since std::vector has continuous memory, &st[0] is the address of the first char in the vector, and thus points to the not null-terminated string that the vector represents, which isn't very helpful outside the function because you can't find the length.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • I like your first sentence. It says it most succinctly---there is never (as far as I can see) a reason to return a `char*`. (There could be cases where a `char const*` is justified. But even those are rare, and probably not of interest except to the expert.) – James Kanze Jul 05 '12 at 07:56
  • @Luchian The length here is not an important factor, all I need to know is, Is it possible to return address of a `st[0]` without defining function as `char*`. – vin Jul 05 '12 at 09:11
  • @vin without defining it as `char*`, you can return a string and do as suggested. Otherwise I don't see any benefit (you could return a `void*` instead, but don't do that). – Luchian Grigore Jul 05 '12 at 09:15
0

That's awkward code, you're expecting 'str' as an argument, but then you return its memory location? Why not return the string itself?

Your code there has a few typos. (Did you mean 'str' when you typed 'st'? If not, then where is 'st' defined?)

As for why you can't define the function as "int" type, that is because an "int" is a different type to "pointer to char".

Personally, I would return 'string', and just have a 'return str' at the end there.

Arafangion
  • 11,517
  • 1
  • 40
  • 72
0

Pointer is pointer, not integer value. Code is right if and only if st is global variable or declared as static in this function. But return string is preferably, than return pointer.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
0

Simple.

string str

is something that contains a bunch characters.

str[0]

return the first character.

Therefore,

&str[0]

gives you the address of the first character, therefore it's a "char *" --- "char" being whatever the pointer points to, "*" being the "address of" part of the pointer. The type of the pointer is about the object being pointed to.

Also, addresses may be just "integers" on the hardware level (everything is an integer... except for integers themselves, they are a bunch of bools), but that doesn't mean anything for a higher level language. For a higher level language, a pointer is a pointer, not an integer.

Treating one as another is almost always an error, and C++11 even added the nullptr keyword so we don't have to rely on the one valid "pointer is an integer" case.

And btw, your code won't work. "str" only exists for the duration of the function, so when the function returns "str" ceases to exist, which means the pointer you have returned points into a big black nowhere.

Chowlett
  • 45,935
  • 20
  • 116
  • 150
Christian Stieber
  • 9,954
  • 24
  • 23
0

Why don't you use string as return type for your function?

First: a pointer is an adress of something lying in memory, so you can't replace it with an integer (only with some dirty tricks).

Second: &st[0] is the adress of the internal buffer the string uses to store its content. When st goes out of scope (or is reused for the next call), it will be overwritten or given back to the heap manager, so the one calling this function will end with some garbage.

Btw, most of your function does unnessesary work which the string class can do by itself (for example copiing strBegin to st).

C. Stoll
  • 376
  • 1
  • 6