1

I tried writing a function to print a char array but for some reason, it only prints out part of the function to the console. For instance:

#include <iostream>
#include <stdio.h>

using namespace std;

void printString(char s[])
{
    int size = sizeof(s) - 1;

    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}

int main()
{
    char fruit[] = "Cherry";
    printString(fruit);
}

leads to the following output:

Che

Regardless of the word I use, only 3 characters print. Any help would be appreciated.

3 Answers3

4

Regardless of the word I use, only 3 characters print. Any help would be appreciated.

int size = sizeof(s) - 1; doesn't do what you think it does.

Since s decays to a pointer at the function call, sizeof(s) always gives you the size of a pointer - 1 (seems to be 32 bit pointers == 4 byte in your case).

Use size_t size = strlen(s); instead:

void printString(char s[]) {
    size_t size = strlen(s);

    for( size_t i = 0; i < size; i++) {
        cout << *(s + i);
    }
}
Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

You can do the following:

void printString(char *s)
{
    while(*s!='\0')
    {
        cout << *s;
        s++ ;
    }
}

Or, You may edit your code as:

#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;

void printString(char s[])
{
    int size = strlen(s);

    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}

int main()
{
    char fruit[] = "Cherry";
    printString(fruit);
}
sunkuet02
  • 2,376
  • 1
  • 26
  • 33
0

Your issue is in the following line:

int size = sizeof(s) - 1;

Since you are using function to print your char array, the char array:

char fruit[] = "Cherry";

decays to a pointer, so sizeof (s) is equivalent of sizeof (char*), which, in your configuration is 4-bytes, so the value of size becomes equal to 3.

To solve this issue you need to pass the size of the array to your function as follows.

#include <iostream>
#include <stdio.h>

using namespace std;

void printString(char s[], int size) // Change here
{
    for( int i = 0; i < size; i++)
    {
        cout << *(s + i);
    }
}

int main()
{
    char fruit[] = "Cherry";
    printString(fruit, sizeof(fruit) / sizeof (fruit[0]) - 1); // Change here
}

And even then, you would need to use such constructs as sizeof(fruit) / sizeof (fruit[0]) to return true size of your array, since sizeof returns the variable size in bytes, so while it would work with char (since the size of a char is one byte, it may not work for other types of arrays (e.g. int arrays).

Update: In case of char arrays, you need to reduce the size you are trying to print by 1, since string literals (or C-like strings in general - char arrays) end with NULL character (char which has value equal to 0), which is the mechanism, by which the end of a string is known. You don't actually need to print it.

Algirdas Preidžius
  • 1,769
  • 3
  • 14
  • 17