1

I received the following question on one of my practice problemswhere it says to determine what is printed by this code:

#include <stdio.h>
int main(){
    int ids[3] = {100,200,300};
    int *salary, salary1, salary2, *salary3;
    salary1 = ids[0] * ids[1];
    salary = &ids[1] ;
    salary2 = *(ids+1)* *(ids+2);
    salary3 = ids+2;
    printf("*salary = %d\nsalary1 = %d\n", *salary, salary1);
    printf("salary2 = %d\nsalary3 = %p\n", salary2, salary3);
}

I am a bit confused about this code. Firstly, in line 4:

    int *salary, salary1, salary2, *salary3;

Why is there an asterisk at the beginning of salary3 if an asterisk was already used in the beginning of the line?

Secondly when it says:

    salary1 = ids[0] * ids[1];

how are we supposed to determine the value of salary1 when we don't know the value of ids[1]?

2
  • 1
    The * only applies to the variable right after it, not all the variables on the line. Commented Feb 15, 2017 at 23:14
  • Because it is not int* salary etc, but int *salary etc. The * qualifies the variable, not the type. Commented Feb 15, 2017 at 23:14

2 Answers 2

2

why is there an asterisk at the beginning of salary3 if an asterisk was already used in the beginning of the line?

The asterisk means the next variable is a pointer. It's the same as:

int *salary;
int salary1;
int salary2;
int *salary3;

but on one line.

how are we supposed to determine the value of salary1 when we don't know the value of ids[1]?

But you do know the value of ids[1]. It's 200.

Sign up to request clarification or add additional context in comments.

3 Comments

I know the value of ids[0] which is 2000, but not ids[1]
@ShoaibAhmed no, ids[0] is 100. Look at the array int ids[3] = {100,200,300}; which defines ids[0] as 100, ids[1] as 200, ids[2] as 300.
oh my bad, i miss read that part. Thank you for pointing that out.
1

Firstly, C declaration syntax is a bit confusing

int *x, y;

Means x is a pointer to an int, y is an int. That's such a source of confusion that virtually every style guide forbids it.

This

  int ids[3] = {100,200,300};

declares an array. ids[0] = 100, ids[1] = 200, ids[2] = 300. It's only really possible to match subscripts to array contents by eye when arrays are small. So this isn't a normal use of arrays. Either you have large read-only tables in global memory, or you create an array at runtime and fill it. However there shouldn't be an issue is ids[1] holding 200, that's how C array syntax works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.