0

Could anyone please explain the difference between the two codes. I asked this question before, but I still did not what is exactly the difference.

#include <stdio.h>
void numberSquare( int b[] );
int main( void )
{
    int a[ 3 ] = { 1, 2, 3 };
    numberSquare( a );
    for( size_t i = 0; i < 3; i++ ) {
        printf( "%d\n", a[ i ] );
    }
}
void numberSquare( int b[] ) {
    for( size_t i = 0; i < 3; i++ ) {
        b[ i ] = b[ i ] * b[ i ];
    }
}
#include <stdio.h>
void numberSquare( int *xPtr );

int main( void )
{
    int a[ 3 ] = { 1, 2, 3 };
    numberSquare( a );
    for( size_t i = 0; i < 3; i++ ) {
        printf( "%d\n", a[ i ] );
    }
}
void numberSquare( int *xPtr ) {
    for( int i = 0; i < 3; i++, ++xPtr ){
        *xPtr = *xPtr * *xPtr;
    }
}
Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
  • 1
    Your question is very ambiguous. Clang 10.0.0, for example, compiles both your code blocks to the exact same assembly: [one](https://godbolt.org/z/hWaExC), [two](https://godbolt.org/z/RnHPyr). So in that sense, there is no difference. I expect this is not the answer you wanted though, so please clarify what kind of answer you _do_ want. – Siguza Jun 21 '20 at 21:19
  • Thanks for your reply. I mean when should I use *xPtr in code 2 or b[] in code 1 when passing arrays to functions. – Ibrahim Jun 21 '20 at 21:23
  • 1
    @Ibrahim They're equivalent when they appear in a parameter list. In a parameter list, the compiler "adjusts" `int b[]` to `int *b`. You can even modify it, e.g. `b++;`, which you can't do with an array. – Tom Karzes Jun 21 '20 at 21:33
  • You often see the same thing with the `argv` argument to `main`. Sometimes you see `char **argv` and sometimes you see `char *argv[]`. They're equivalent in a parameter list. – Tom Karzes Jun 21 '20 at 21:35

0 Answers0