0

What is the difference between char* c, and char *c? What is wrong in this code?

#include<iostream>
#define num 2
using namespace std;
int main (){
    char *c="HelloWorld!!!";
    cout<<*(c+num);
    return 0;
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • Your compiler should have asked you to add a `const` at the declaration of `c`. – Bob__ Jun 18 '20 at 05:32
  • 1
    What do you mean `& char *c`? – 김선달 Jun 18 '20 at 05:37
  • _What is wrong in this code?_ Beside of the missing `const`, there is nothing wrong with the code. It outputs `l` ([Demo on coliru](http://coliru.stacked-crooked.com/a/3ee14aa8e2d2b461)) which is the third letter in `"HelloWorld!!!"` (i.e. the character at `c + 2`). What did you expect? – Scheff's Cat Jun 18 '20 at 05:39
  • If you want to print the string literal from the third letters until the end, you should remove the * in front of c+num. – Gerardo Zinno Jun 18 '20 at 05:41
  • 1
    As the answers have noted, there is no difference between `char *c` and `char* c` - but even so STICK WITH THE FORMER ! The `*` belongs to the variable, not the type. For example, if you have `char* c,d,e`, then only `c` is the `char*` .... d and e are of `char` only. – racraman Jun 18 '20 at 06:02
  • Does this answer your question? [Declaring pointers; asterisk on the left or right of the space between the type and name?](https://stackoverflow.com/questions/2660633/declaring-pointers-asterisk-on-the-left-or-right-of-the-space-between-the-type) – t.niese Jun 18 '20 at 06:08
  • @racraman This is like spaces vs. tabs. Both formats have their validity. I'd argue the type is `char*`, as that's how the compiler sees it, not `char` that happens to be a pointer. Whatever form you prefer, it's just best to be consistent about it, and always use the same approach. Declaring multiple variables at once is asking for trouble, as you note. – tadman Jun 18 '20 at 07:08
  • Tip: You almost always mean `c[num]` instead of `*(c + num)`. – tadman Jun 18 '20 at 07:09
  • @tadman the point is that the compiler associates the * with the variable, which is why d and e are just `char` (and of course whitespace is ignored, which is why `char* c` and `char *c` are both accepted). Coding styles should follow what the compiler is doing, otherwise people may get bitten by d and e not being what they think. – racraman Jun 18 '20 at 07:25

4 Answers4

1

in c++, string literal is implemented by const char* . Additionally, the compiler will not distinguish

char* c;

and

char *c;

as they have same meaning (pointer to char)

K.R.Park
  • 1,015
  • 1
  • 4
  • 18
0

There is absolutly no difference between char* c and char *c the problem with your code is that "HelloWorld" is a const char* so you either have to cast it to a char* or store it in a const char variable. Also I wouldn't define that macro, just store that number in a variable(constexpr variable if you want compile time evaluation) it's much easier to read

#include<iostream>
using namespace std;
int main() {
    constexpr int num = 2;
    char* c = (char*)"HelloWorld!!!";
    const char* c2 = "HelloWorld!!!";
    cout << *(c + num);
    return 0;
}
SzymonO
  • 432
  • 3
  • 15
0

If you compile your program with the -Wall flag enabled, you'll see the following error message:

warning: ISO C++11 does not allow conversion from string literal
      to 'char *' [-Wwritable-strings]
    char *c="HelloWorld!!!";

you should make the c variable a const char * in order to make the warning disappear since the string literal is implemented as such type, differently from C where char* would suffice.

Note: You could simply use the auto keyword and let the compiler find the right type:

auto c = "HelloWorld!!!"
Gerardo Zinno
  • 1,518
  • 1
  • 13
  • 35
0

There is no difference between char* and char *, but there is difference between char& and char*, so please edit your question and be more specific, say what you are expecting to happen, because your code is doing what you wrote, so I don't know if maybe want to concatenate array of chars with 2. If this is the case, than I will suggest you to use <string>, in this library you can use operator+() for concatenation reference.

What you are doing in your code is: you create array, and then you print something on address c + 2. That is 'l'. When I run I get this. As someone sayed before you must be careful because const char* can not be used to initialize char*, reference.

If you really want to change that string you can do something like this:

 #include<iostream>
 #include <stdlib.h>

 #define num 2

using namespace std;
int main() {
    const char* c = "HelloWorld!!!";
    char* str;
    int n = 0;
    while (true)
    {
        if (c[n++] == '\0') // '\0' is character for terminating string
        {
            break;
        }

    }
    str = (char*)calloc(n + 1, sizeof(char));
    for (int i = 0; i <= n; i++)
    {
        if (i < n - 1)
        {
            str[i] = c[i];
        }
        else
        {
            if (i == n - 1)
            {
                str[i] = (char)('0' + num);// with this sum you wil get ascii code of '2' and write it in str + n - 1
            }
            else
            {
                str[i] = '\0';
            }
        }
    }
    cout << str;

    //cout << *(c + num);
    return 0;
}

There is a difference between string and char*. In C/C++ you can only have array of chars. You can perform any primitive operation on char as you can on int. But you can't perform operation directly on array if you don't call your own function. For that reason you should use libraries to perform operations such as concatenation, comparing strings, or something else. If you prefer to work directly with char* you should use <string.h>, but if you want to be more comfortable you can use <string> and create string as object.