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.