Gerard G
Gerard G

Reputation: 3463

printing with Pointers

I'm trying to figure out how this code works can someone help me run through the processes going on in here: Like what does *(++cp) mean? In my mind I'm thinking its = str + 7 And *oddNums = 1 the start of the oddNums array. so that str + 8 after the math which = ld Sorry I really don't understand it.

int main ()
{
    int oddNums[5] = {1, 3, 5, 7, 9};
    char str[20] = "Hello world";
    int *ip = oddNums;
    char *cp = str + 6; 

    printf("\n.%c",*(++cp) + *oddNums);


    return EXIT_SUCCESS;
}

Upvotes: 2

Views: 117

Answers (2)

lurker
lurker

Reputation: 58244

int oddNums[5] = {1, 3, 5, 7, 9};

This creates an array of 5 ints. If you refer to oddNums[2], that will give you 5. If you refer to oddNums, that's a pointer to int that points to the beginning of the array. So *oddNums would give you 1, *(oddNums+1) would give you 3, and so on.

char str[20] = "Hello world";

See my discussion about oddNums above, which apply here. This is also a string, which means it ends in a zero after the letter d.

int *ip = oddNums;

Remember oddNums is a pointer to an integer. So this just makes a copy of it to another int pointer called ip.

char *cp = str + 6; 

This assigns the value (str + 6) to the char pointer cp. str is a char pointer to the string defined above. It points to the beginning of the string "Hello world".

printf("\n.%d",*(++cp) + *oddNums);

*(++cp) means to get what cp points to after cp has been incremented. In other words, preincrement cp, then get what it points to. cp was pointing to str + 6, which was the w in the string. But ++cp makes it point to the 'o' in "world". So *(++cp) will yield an 'o'.

Then 'o' is getting added to whatever oddNums points to. Nothing has happened to oddNums since we started, so it still points to the 1 in the integer array. *oddNums says "give me what oddNums points to", which is 1.

So the value of *(++cp) + *oddNums will be 'o' + 1, which is 'p' (the next letter in the ASCII sequence).

Interestingly, the printf says to "print the thing you're given as an integer after you print a line feed and a period" ("\n.%d"). Therefore, the result will be...... .112. I think.

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361605

printf("\n.%d",*(++cp) + *oddNums);

Break it down. This is equivalent to:

++cp;
printf("\n.%d", *cp + *oddNums);

The first statement increments cp so now cp == str + 7. Replacing cp in the modified printf yields:

printf("\n.%d", *(str + 7) + *oddNums);

*(str + 7) is the same as str[7], which is the single character 'o'. *oddNums is 1. Performing one final substitution yields:

printf("\n.%d", 'o' + 1);

It prints the character 'p'. Or rather, it prints the ASCII value of 'p'—112—since we have a %d format rather than %c.

Upvotes: 9

Related Questions