Search code examples
c++stringcharsizeoffunction-parameter

Char has a different size than a string


I was working with a program that uses a function to set a new value in the registry, I used a const char * to get the value. However, the size of the value is only four bytes. I've tried to use std::string as a parameter instead, it didn't work.
I have a small example to show you what I'm talking about, and rather than solving my problem with the function I'd like to know the reason it does this.

#include <iostream>


void test(const char * input)
{
    std::cout << input;
    std::cout << "\n" << sizeof("THIS IS A TEST") << "\n" << sizeof(input) << "\n";
    /* The code above prints out the  size of an explicit string (THIS IS A TEST), which is 15. */
    /* It then prints out the size of input, which is 4.*/

    int sum = 0;
    for(int i = 0; i < 15; i++) //Printed out each character, added the size of each to sum and printed it out.
    //The result was 15.
    {
        sum += sizeof(input[i]);
        std::cout << input[i];
    }
    std::cout << "\n" << sum;
}
int main(int argc, char * argv[])
{
    test("THIS IS A TEST");
    std::cin.get();
    return 0;
}

Output:
THIS IS A TEST
15
4
THIS IS A TEST
15

What's the correct way to get string parameters? Do I have to loop through the whole array of characters and print each to a string (the value in the registry was only the first four bytes of the char)? Or can I use std::string as a parameter instead?
I wasn't sure if this was SO material, but I decided to post here as I consider this to be one of my best sources for programming related information.


Solution

  • sizeof(input) is the size of a const char* What you want is strlen(input) + 1

    sizeof("THIS IS A TEST") is size of a const char[]. sizeof gives the size of the array when passed an array type which is why it is 15 .

    For std::string use length()