Function parameters are its local variables.
You can imagine the function call and its definition the following way
char *name1 = "test_name";
switch_name(name1);
//...
void switch_name( /* char* name */ )
{
char *name = name1;
name= "testv2";
}
As you can see the original variable name1
was not changed in the function. It is the variable name
that is the parameter that was changed in the function.
You have to pass the original variable by reference if you are going to change it in the function.
For example
#include <stdio.h>
void switch_name( char ** name)
{
*name= "testv2";
}
int main( void )
{
char *name1 = "test_name";
printf("%s\n", name1);
switch_name( &name1 );
printf("%s\n", name1);
}
Compare the above program with the following program
#include <stdio.h>
#include <string.h>
void switch_name( char* name )
{
strcpy( name, "testv2" );
}
int main(void)
{
char s[] = "test_name";
char *name1 = s;
printf( "%s\n", name1 );
switch_name( name1 );
printf( "%s\n", name1 );
return 0;
}
In the first program you are going to reassign the original pointer itself using a function.
In the second program it is the data pointed to by the pointer that are reassigned using the standard C function strcpy
.
Take into account that according to the C Standard the function main
without parameters shall be declared like
int main( void )