0

I'm solving C programming quiz.

The quiz problem was "what is the output of the following code snnipet?"

uint32_t v = 0xdeadbeef;
printf("%02x", (char *) v[0]);

or uint64_t? 

Honestly I didn't understand the problem, so I tested on my local machine.

#include<stdio.h>
#include<stdint.h>

int main() {
    uint32_t v = 0xdeadbeef;
    printf("%02x", (char *) v[0]);    /* (1) */

    int64_t w = 0xdeadbeef;
    printf("%02x", (char *) w[0]);    /* (2) */

}

I'm getting compile error on (1) and (2).

Here is the error message

num1.c: In function ‘main’: error: subscripted value is neither array nor pointer nor vector

So for the question on this post, How can I test this code without compile error?

Expected output : de, ad, be, ef, or 00

19
  • The code's a little buggy -- you'll need to cast v, not v[0]. That is, ((char*)v)[0]. That might also give you an idea as to the problem. Commented Dec 12, 2017 at 2:40
  • Did you copy-and-paste the quiz problem? Either the quiz is incorrect, or the quiz is correct and you copied it incorrectly. Commented Dec 12, 2017 at 2:42
  • 1
    This should probably be ((char *) &v)[0]. Then it would output either de or ef depending on endianness. Commented Dec 12, 2017 at 2:50
  • 1
    The compiler is correct. The code in the quiz problem is wrong. The only way it makes sense is to change (char *)v[0] to ((char *)&v)[0] -- or, more likely, ((unsigned char *)&v)[0] Commented Dec 12, 2017 at 2:57
  • 1
    @JohnBaek yes, because you subscripted a value (v) which is neither array nor pointer nor vector. The subscript operator requires one of those things as operand. Commented Dec 12, 2017 at 3:05

1 Answer 1

1

I think the problem asks about the first byte of four bytes uint32_t arranged in memory layout. That depends on endianness. If you want to find out the output, you may check this code.

#include<stdio.h>
#include<stdint.h>

int main() {
    uint32_t v = 0xdeadbeef;
    char* pv = (char*)&v;
    printf("%02x\n", (uint8_t)pv[0]);
}
Sign up to request clarification or add additional context in comments.

7 Comments

Yeah it's working. it's printing ef. It seems right answer.
And at the same time, I'm very confused.
What is the confusion?
That depends on endianness. I learned Endianness is the order of memory arrangement (I learned it about 3 years ago so I may misunderstand what it means). And how is it related to your answer?
If you machine is little endian, then it will show ef. And if it is big endian, it will show de. Please check endianness
|

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.