Search code examples
cfunctionpointerstestingprogram-entry-point

Testing function with pointer parameter C


I started learning C this week and here is the first difficulty I'm encountering with pointers.

I would like to test this function:

void    ft_ultimate_div_mod(int *a, int *b)
    {
        int *tmp;

        if (b != 0)
        {
            *tmp = *a % *b;
            *a = *a / *b;
            *b = *tmp;
        } 
}

But I can't figure out the main using pointers. My program is not printing anything with:

int     main(void)
{
    int *a;
    int *b;

    *a = 5;
    *b = 3;

    ft_ultimate_div_mod(a, b);
    printf("%d", *a);
    printf("%d", *b);

    return (0);

}

What can I do? Thx!


Solution

  • For starters it does not make sense to declare the variable tmp as having the type int *. The variable is used to store an object of the type int so it has to have the type int. Otherwise you are using an uninitialized pointer with an indeterminate value that results in undefined behavior of the program.

    Also as the variable is used in the compound statement of the if statement then it should be declared in the blco scope of the if statement.

    These declarations in main

    int *a;
    int *b;
    

    als do not make sense.

    What you mean is the following.

    #include <stdio.h>
    
    void    ft_ultimate_div_mod(int *a, int *b)
    {
        if ( *b != 0 )
        {
            int tmp = *a % *b;
            *a = *a / *b;
            *b = tmp;
        } 
    }
    
    int main(void) 
    {
        int a = 10;
        int b = 3;
    
        ft_ultimate_div_mod( &a, &b );
    
        printf( "%d %d\n", a, b );
    
        return 0;
    }
    

    The function ft_ultimate_div_mod excepts its arguments by reference because it tries to change their original values.