Wizzardzz
Wizzardzz

Reputation: 841

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!

Upvotes: 0

Views: 1447

Answers (2)

fordp
fordp

Reputation: 21

You declare int *tmp in your function. That is a pointer to an int sized bit of memory that can store an int. You never point it anywhere however so *tmp = *a % *b; will do a mod of a an b and then crash when it stores it using an uninitialized pointer.

Change the *tmp to just tmp so then your code becomes:

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

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

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

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.

Upvotes: 1

Related Questions