Computer Scientist

Wednesday, 15 December 2010

Discussion on Array size, String length.

This is an revision concentrating two functions, sizeof() and strlen().

There are several manners for a programmer to define a string in C/C++ programs.

  1. char pointer: char *string; 
  2. char array: char string[100];

In order to initialize them, the following steps work.

  • define string immediately if we know what we want to define.
        char string[] = "This is what we want to defined";
        char *string = "This is what we want to defined";
  • define string first and then give the specific number afterwards.
        char string[100];
        string = "This is what we want to defined";
            CAUTION:<<This is not allowed in C++, can not assign an array to another array>>
            INSTEAD: strcpy(string, "This is what we want to defined");

        char *string;
        string = "This is what we want to defined";

In the following part, I give some different defined strings in my code. The print out is the results of two functions, sizeof() and strlen.

Here is the code:

    char *test;
    char test2[100];


    test = "This is what we want to define";
    char buffer []= "This is what we want to define";
    strcpy(test2, "This is what we want to define");
   
    std::cout << "test sizeof " << sizeof(test) << "\n";
    std::cout << "test strlen " << strlen(test) << "\n";
   
    std::cout << "buffer sizeof " << sizeof(buffer) << "\n";
    std::cout << "buffer strlen " << strlen(buffer) << "\n";
   
    std::cout << "test2 sizeof " << sizeof (test2) << "\n";
    std::cout << "test2 strlen " << strlen(test2) << "\n";

The print out is:

   test sizeof 4
   test strlen 30
   buffer sizeof 31
   buffer strlen 30
   test2 sizeof 100
   test2 strlen 30

Another aspect of the difference between strlen() and sizeof() is that strlen needs a function call to determine the string length, however, sizeof is able to give the length during the compile process. The buffer's example demonstrates this argument quite well. But, the prerequisite is that the sizeof() is able to give rather correct string length. The string should be defined and initialized as buffer example dose. In this case, bear in mind that sizeof will include the '\0' but strlent will not.

Hopefully, this makes clear of the usage of string.