How to solve "subscripted value is neither array nor pointer nor vector"

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

c
asked on Stack Overflow Dec 12, 2017 by hellofanengineer • edited Dec 12, 2017 by Charles Duffy

1 Answer

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]);
}
answered on Stack Overflow Dec 12, 2017 by abdullah

User contributions licensed under CC BY-SA 3.0