Problem with function that provides a range of numbers (C). Why?

Viewed 50

I have created a function that provides a range of numbers based off of one number, and the amount of numbers you want to get that are away from the number (I know, that explanation was kind of vague, so here is an example):

Number of origin: 10
Number of numbers to count away from the origin: 5
Output:
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

So here is the code:

#include <stdio.h>
#include <stdlib.h>

void plusMinus(int*change, int num, int funcTo){

    int range = funcTo * 2;
    int start = num - funcTo;
    int i;
    for (i=0; i<=range; i++){
        change[i] = start + i;
    }
}

int main()
{
    int* pointer;
    plusMinus(&pointer, 250, 5);
    int x;
    for (x=0; x<=10; x++){
        printf("%d\n", &pointer[x]);
    }
    return 0;
}

and here is the desired output:

245
246
247
248
249
250
251
252
253
254
255

and here is the current output:

245
249
253
257
261
265
269
273
277
281
285

The code is also returning two warnings, but I have no idea as to what they mean. Here is the first one:

warning: passing argument 1 of 'plusMinus' from incompatible pointer type [-Wincompatible-pointer-types]

and here is the second:

warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *' [-Wformat=]
1 Answers

The first function parameter has the type int *

void plusMinus(int*change, int num, int funcTo){

but you are passing an argument of the type int **

int* pointer;
plusMinus(&pointer, 250, 5);

Moreover the pointer pointer is uninitialized and has indeterminate value. As a result the program has undefined behavior.

In this call of printf

printf("%d\n", &pointer[x]);

the conversion specifier %d expects an object of the type int while you are passing an object of the type int *.

Here is your updated program

#include <stdio.h>

void plusMinus( int *a, int num, int funcTo )
{
    int range = 2 * funcTo + 1;
    int start = num - funcTo;

    for ( int i = 0; i <range; i++ )
    {
        a[i] = start + i;
    }
}

int main(void) 
{
    int funcTo = 5;
    int a[2 * funcTo + 1];

    plusMinus( a, 250, funcTo );

    for ( int i = 0; i  < 2 * funcTo + 1; i++ )
    {
        printf( "%d ",  a[i] );
    }
    putchar( '\n' );

    return 0;
}

Its output is

245 246 247 248 249 250 251 252 253 254 255 

It is more interesting to write the function as a recursive function.

Here you are.

#include <stdio.h>

void plusMinus( int *a, int num, int funcTo )
{
    a[0] = num - funcTo;

    if ( funcTo ) 
    {
        plusMinus( a + 1, num, funcTo - 1 );

        a[2 * funcTo] = num + funcTo;
    }
}

int main(void) 
{
    int funcTo = 5;
    int a[2 * funcTo + 1];

    plusMinus( a, 250, funcTo );

    for ( int i = 0; i  < 2 * funcTo + 1; i++ )
    {
        printf( "%d ",  a[i] );
    }
    putchar( '\n' );

    return 0;
}

The program output is the same as shown above.

245 246 247 248 249 250 251 252 253 254 255 
Related