So I have an C string (array of chars) in my main method, when I pass it as parameter into another method, its size changes.
void method(char* arr){
printf( "%u\n", sizeof(arr) ); //returns 4, in my program.
arr = "hello "; //executes just fine
char arr2[9] = "people";
strcat(arr, arr2); // (1) here is where it crashes down
int i = 0; while(i < sizeof(arr2)){ arr[i+6] = arr2[i]; i++;} // (2) this causes it to crashdown too
}
int main(){
char array[33];
printf("%u\n", sizeof(array) ); //returns 33, in my program.
method(array);
}
Why does this happen?, how can I fix it? Does this mean I cannot add more values to the C string? I suspect this may be the cause of the constant crashdown of my program (whenever I try to add n). Neither does the line marked by (1) nor (2) works. Is there a workaround?
Here is what happens:
In main(), you're applying sizeof() to the array, so you get the size of the array.
When main() calls method(), the array decays into a pointer (since method() takes a pointer).
In method(), you are applying sizeof() to the pointer, so you get the size of the pointer.
To fix, pass the actual allocated size of arr into method() as an additional argument, and use that argument as a limit on how much stuff you're permitted to write into arr.
As a side note, the following doesn't do what you expect:
arr = "hello "; //executes just fine
This doesn't modify the underlying array; it simply re-points arr to the string literal. You should be using strncpy() instead of the assignment.
You're doing sizeof on a pointer, not on a array. You cannot pass an array by value into a function. You just can't.
You're then replacing the local copy of said pointer with a new one that points to "hello". Then expecting to be able to get the 8th character of the string "hello" is obviously not going to work.
std::string and std::vector.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With