简体   繁体   中英

C - Pointer inside a function pointing to an array displaying invalid character

I have an array product[6] and a pointer (*productPtr) pointing to this array. When I pass the pointer as an argument to a function called productCheck and try to print one of the characters, I get an invalid reading of the characters from the product array. Any help as to why this is happening is greatly appreciated. For example if i = 3, instead of reading 'u', the output is '{'.

int i = 3;    
char product[6] = "xddua";
char * productPtr;
productPtr = product;


bool productCheck(int i, char * productPtr);


productOk = productCheck(i, &product);


bool productCheck(int i, char * productPtr)
{    
    printf("product is %c\n", *productPtr + i);

The function has the second parameter of the type char * .

bool productCheck(int i, char * productPtr);

You are calling the function passing expression the expression &product as the second argument

productOk = productCheck(i, &product);

As the array product is declared like

char product[6] = "xddua";

then the type of the expression ^product is char ( * )[6] . That is the type of the argument is not compatible with the type of the function parameter.

You need to call the function either like

productOk = productCheck(i, product);

or like

productOk = productCheck(i, productPtr);

Within the function dereferencing the passed value of the expression &product in this statement

printf("product is %c\n", *productPtr + i);

And then to the result expression you are adding the value i instead of at first to add the value i to the pointer and then to dereference the pointer expression..

Thus you need to call the function like

productOk = productCheck(i, product);

or like

productOk = productCheck(i, productPtr);

and within the function you need to write either

printf("product is %c\n", *( productPtr + i ) );

or

printf("product is %c\n", productPtr[i] );

The unary * operator has higher precedence than + operator.

*productPtr + i first reads what is pointed at by productPtr , then adds i to the value read.

To access another element, You should write *(producePtr + i) or productPtr[i] .

Also the argument &product is not good. Most arrays in expressions are automatically converted to pointers to the first element (one of the exceptions is the operand of unary & ), so it should be product to pass char* value.

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