0

What is wrong with this code? input has always the length of 4 in my function test, no matter if my string is actually longer or shorter.

#include <iostream>
#include <string>
using namespace std;

void test(char arr[]){
    string input;

    input = arr[0];
    for (int i=1; i<sizeof(arr)/sizeof(char); i++){input=input+arr[i];}

    cout << input << endl;
    cout << "length: " << input.length() << endl;
}


int main(){
    string input;
    cout << "String: " << endl;
    getline(cin, input);
    char arr[input.length()];
    for(int i=0; i<input.length(); i++) {arr[i] = input[i];}

    test(arr);
}
Ixrec
  • 966
  • 1
  • 7
  • 20
Christian
  • 169
  • 7
  • input=input+arr[i]; not sure if you can do that. You can concatenate strings, but not char arrays – Nick Jan 21 '15 at 22:38
  • char arr[input.length()]; ? The code won't compile on this line. – Matt Jan 21 '15 at 22:40
  • it will compile on GCC, also it probably will concatenate. seems @pow 's answer is correct one, because p[] is same as *p – Nick Jan 21 '15 at 22:42
  • 3
    Welcome to wonderful world of C arrays! Now I suggest you retreat slowly, while avoiding sudden movements, and convert your code to use `std::vector` (for dynamic arrays) or sometimes `std::array` (for arrays of fixed length). – hyde Jan 21 '15 at 22:50

3 Answers3

5

Arrays decays to pointers while passing to function

sizeof(arr) will give you size of char*

P0W
  • 46,614
  • 9
  • 72
  • 119
3

Don't use arrays; instead prefer std::vector. When you think you're passing an array to a function, you're actually passing a pointer, and on your architecture pointers are 4 bytes wide. char arr[] is a weird way of spelling char* arr in function parameters. This is known as “pointer decay”.

If you really have to use raw pointers, pass in the length as an additional parameter:

void test(size_t length, char* arr) {
    ...
}

test(input.length(), arr);
amon
  • 57,091
  • 2
  • 89
  • 149
0

You are taking the size of the pointer when you do sizeof(arr) in the function. Passing an array to a function like you did is a syntactic sugar, effectively it is passing a pointer to the array and you are just taking the size of the pointer (which happens to be 4bytes on the machine you are using). You need to pass the size of the array to the function in another parameter or use a convenient STL container.

Also take a look at this question for more details.

Community
  • 1
  • 1
Mustafa
  • 1,814
  • 3
  • 17
  • 25