-5

Someone can tell me different between this code:

char *s1 ="Con Chim Non";

and this one:

char *s=new char[100];
gets(s);

Then, I add the word: "Con Chim Non".

After, I build a code that change value of the pointer. In first code, I got a problem about the address. The second is right. And this is my code:

void Strlwr(char *s)
{
    if (s == NULL )
        return ;
    for (int i = 0; s[i] != '\0'; ++i)
    {
        if ( s[i] <= 'Z' && s[i] >= 'A')
            s[i] = s[i]+32;
    }
}

And someone can tell me why the first is wrong.

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
  • The difference is that the first is not valid C++11, nor C++14, and the second is not valid C++14. – chris Jun 09 '14 at 13:54
  • Can you explain clearly for me?. I used the second and got a right result. – user3722548 Jun 09 '14 at 14:03
  • `gets` has been removed from C++. It's a terrible function that does nothing to prevent buffer overruns. Even C didn't want it and got rid of it in C11. – chris Jun 09 '14 at 14:09

1 Answers1

1

The first example:

char *s1 ="Con Chim Non";

You declare a pointer to a text literal, which is constant. Text literals cannot be modified.

The proper syntax is:

char const * s1 = "Con Chim Non";

Note the const.

In your second example, you are declaring, reserving memory for 100 characters in dynamic memory:

char *s=new char[100];
gets(s);

You are then getting an unknown amount of characters from the input and placing them into the array.

Since you are programming in the C++ language, you should refrain from this kind of text handling and use the safer std::string data type.

For example, the gets function will read an unknown amount of characters from the console into an array. If you declare an array of 4 characters and type in 10, you will have a buffer overflow, which is very bad.

The std::string class will expand as necessary to contain the content. It will also manage memory reallocation.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154