Menu

Simple String Questions

2003-02-06
2012-09-26
  • Nobody/Anonymous

    Hi,

    I have 2 questions about strings.

    1) Why does the following code give me an illegal operation -

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

    using namespace std;

    int main(int argc, char *argv[])
    {    
          char *string = "Test";
         
          string[0] = 'A';
          cout << string << endl;     
     
          system("PAUSE");   
          return 0;
    }

    If I take out the string[0] line it works. How would you change one letter.

    2) How would you make a character = NULL. I have seen on some tutorials where they say buffer[num] = NULL. This works in VC but in DevC++ it says trying to make a non pointer type "char" NULL. This makes sense but what should you use for a null character.

    Thanks a lot

     
    • Anonymous

      Anonymous - 2003-02-06

      Change string declaration thus:

      char string[] = "Test";

      Your declaration declared a pointer to a string constant, and you cannot change the constant. This creates an array and initialises it with "Test".

      Caution: the compiler will allocate 5 bytes to string (four characters of "Test", plus the NUL terminator). You may not access characters beyond string[4], and if you change string[4] to be anything other than zero (NUL or '\0'), it will no longer be interpreted as a C style string. If you want to allocate more space make the size explicit:

      char string[20] = "Test";

      In C NULL is a pointer not a character, however it is equal to zero, and some compilers will do an automatic type conversion - they chould not!

      You can simply assign it with zero (0) since 0 can samedly be type converted to any type automatically. However it is better to be clear that you are using characters and the character constant '\0' (single quotes) is alwaus of type char.

      You could define an constant NUL. The thee letter abbreviation is conventional for ASCII control characters, and differentiates it from the NULL pointer. But this may be confusing, so a better name would be NUL_CHAR

      The following are all valid:
      character = 0 ;          // auto type conversion
      character = (char)0 ;  // explicit type conversion
      character = '\0' ;        // correct type to start with

      #define NUL_CHAR '\0'         // readable definition
      character = NUL_CHAR ;     // self documenting code

      The first one is simplest, any argument however world be just 'religous' since all are correct under ANSI C.

       
    • Nobody/Anonymous

      Thanks a lot, I'll try that out :)

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.