8
string line = "blerdy blah";
for (int i = 0; i < string.size(); i++)
{

    line[i] != "n";
}

With this I get the error "cannot convert from char to const char *"

If I replace the last line with

line[i] != *"n";

It works. I get why in one sense, I'm dereferencing a pointer. What I don't get is why it's a pointer in the first place. Is any char written like this actually a pointer to one char somewhere? Like the program has one set of every symbol somewhere and this is what I'm pointing to?

If this is the case, can I do silly things like make the 'n' pointer point to something else?

Dollarslice
  • 9,917
  • 22
  • 59
  • 87

6 Answers6

13

You have to compare char with char in this case:

line[i] != 'n';

When you say *"n" you actually dereference the first element of the char array with n and \0 elements inside it, which gives you n, that's why it works, but you don't want to write it like that.

10

"n" is not a character literal, it is a string literal. You want 'n'.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

"n" is a char array (string). While 'n' is a char.

Xyand
  • 4,470
  • 4
  • 36
  • 63
2

"n" is a so called string literal, which has the type const char[2]. string::operator[] (actually basic_string<char>::operator[] returns a const char& or char& depending on the picked overload (the second one in this case). You cannot compare those types. What you want want to compare the result of operator[] to is a character literal, which is written as 'n'.

For your second question

"n" has type const char[2], dereferencing it gives you a char (the first character in the array pointed to). This is equivalent to "n"[0].

pmr
  • 58,701
  • 10
  • 113
  • 156
1

Change "n" to 'n'. The difference is that the former is a const char* whereas the latter is char. Since you want to compare one char to another, the latter is the correct form to use.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Why and how this works

Start with "n": lexically it is a null-terminated string literal, which means that the compiler will end up treating it as a char* pointing to a section of memory that holds the string "n".

So when you write *"n", what happens is that you are dereferencing a char* that points to "n", which means that the result of the expression will be 'n' (of type char). That's why the comparison to line[i] (which is also a char) works.

This pointer to "n" is a compile-time constant (so you can't change it) and in all likelihood will point to a read-only memory page (so you won't be able to change what it points to at runtime either).

What you should do instead

line[i] != 'n'; // compare char to char
Jon
  • 428,835
  • 81
  • 738
  • 806