简体   繁体   中英

Pass address to pointer function

I wanted to write a general function to print any array

I don't understand why the function with pointers don't work and the function with no pointers work

I also get the warning: value computed is not used [-Wunused-value]|

here is the code:

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

void prt(int *start,int *x_size,int *i_count);

void prt2(int *s_tart, int s_ize,int c_ounter);

int main()
{
    int arr[]= {10,5,32};

int x=3;
int i=0;

printf("Print using pointers result is:\n");

prt(arr,&x,&i);

printf("Print without using pointers result is:\n");

prt2(arr,x,i);

return 0;
}

void prt(int *start,int *x_size,int *i_count)
{
     for(*i_count=0; *i_count<*x_size; *i_count++)
{
    printf("%d\n\n",start[*i_count]);
}

}
void prt2(int *s_tart, int s_ize,int c_ounter)
{
     for(c_ounter=0; c_ounter<s_ize; c_ounter++)
    {
        printf("%d\n",s_tart[c_ounter]);
    }
}

the source of the problem is the 'precedence' of the operators in C.

The '++/increment' operator has a higher precedence (handled before) the '*/dereference' operator

This expression: '*i_count++' results in the pointer being incremented, then the resulting pointer being dereferenced.

The desired operation was to dereference the pointer then increment the target.

Therefore the expression should be: '(*i_count)++' so the dereference occurs first.

*i_count++ means the pointer move to next, you hope the value of pointer increase.

you can use (*i_count)++ instead of *i_count++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM