简体   繁体   中英

How to solve “subscripted value is neither array nor pointer nor vector”

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

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]);
}

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