C language: the value passed
C language function is transmitted by way of reference passed by value:
1-1
int swap( int a, int b )
{
int c = a;
b = a;
a = c;
}
int swapp( int *a, int *b )
{
int c = *a;
*a = *b;
*b = c;
}
int main ( )
{
int a = 5, b = 7;
swap ( a, b );
printf( "%d %d\n", a, b );
swapp( &a, &b );
printf( "%d %d\n", a, b );
return 0;
}
Output:
. 5. 7
. 7. 5
for example, the difference between swap and swap function swapp: the values are passed
swap transfer function that copies values of a and b, the values of a and b is not the main function of the exchange.
swapp disposal function is, copy the address of a and b, a and b in fact, the exchange address.
as the picture shows
Common Errors
When passing pointers (1-2): foo is passed a copy of the address, c will not affect a change point.
foo function (1-3): If using the malloc or calloc foo for memory, the return value is not assigned to c a, and easy to leak memory access violation.
foo function (1-4): When using realloc, expand or reduce the memory space, occurs if nptr = realloc (ptr, size), ptr nptr not equal, causing mistakes and memory leak when pre equal nprE, not. An error occurred. Error easily be found
1-2
int w = 10;
void foo( int *c ){
printf( "c:%p\n", c);
c = &w;
printf( "c:%p\n", c );
}
int main ( )
{
int k = 0;
int *a = &k;
printf( "k:%p\n", &k );
printf( "a:%p\n", a );
foo( a );
printf("a:%p\n", a );
return 0;
}
Output
K: 0xbfafefd8
A: 0xbfafefd8
C: 0xbfafefd8
C: 0x804a020
A: 0xbfafefd8
1-3
void foo( int *c, int m ){
c = malloc( m * sizeof( int ) );
}
修改
void foo( int **c , int m ){
*c = malloc( m * sizeof( int ) );
}
int main( ){
int *w;
foo( w, m );
修改:
foo( &w, m );
}
1
1-4
void foo( int *c, int m ){
c = realloc( c, m * sizeof( int ) );
}
修改
void foo( int **c , int m ){
*c = realloc( *c, m * sizeof( int ) );
}
int main( ){
int *w;
foo( w, m );
修改:
foo( &w, m );
}