Alex Rivera | Logout

Changing an array with a function in C?

Asked 2011-04-10T12:51:37.137
15

I want to call a function and I want that function to change the contents of a string or array in the program to a constant.

Psuedocode:

some_array = "hello"
print some_array   #prints "hello"
changeArray(some_array)
print some_array  #prints "bingo"

I know I have to pass the pointer to that function. Here's what I wrote,

void changeArray(char *arr){
    arr = "bingo";
}

int main(int argc, const char* argv[]){
    char *blah = "hello";
    printf("Array is %s\n",blah);
    changeArray(blah);
    printf("Array is %s\n",blah);
    return EXIT_SUCCESS;
}

How can I do this?

Edit
Report

1 Answer

0

You need to pass a pointer to array not the array itself.

Another thing: add a control condition to your function. think: what will happen if "bingo" will be bigger than strlen(some_array) ? it will give you an error because in C you must malloc it if you need the array size to be dynamic !

answered 2011-04-10T13:38:22.623

Your Answer