Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C array not working properly

Tags:

c

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?

like image 939
Sofia Alegre Avatar asked Mar 10 '26 07:03

Sofia Alegre


2 Answers

Here is what happens:

  1. In main(), you're applying sizeof() to the array, so you get the size of the array.

  2. When main() calls method(), the array decays into a pointer (since method() takes a pointer).

  3. 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.

like image 62
NPE Avatar answered Mar 12 '26 03:03

NPE


  1. 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.

  2. 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.

    • You're in C++. Use std::string and std::vector.
like image 22
Lightness Races in Orbit Avatar answered Mar 12 '26 02:03

Lightness Races in Orbit