4

How does this code work?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

sc[] = bla bla bla a bunch of hex;

int main(void)
{  
   (*(void(*)()) sc)();
}

This (*(void(*)()) sc)(); specifically is what I'm unsure of.

jscs
  • 63,694
  • 13
  • 151
  • 195
user793663
  • 69
  • 1
  • I'm also unsure what it does. – PengOne Jun 11 '11 at 04:30
  • 2
    What's with the down votes & "not a real question" votes to close? It's a good question - the code is valid C, and it's easy to see why it's difficult to understand. – Sherm Pendley Jun 11 '11 at 04:39
  • 1
    Rather than simply asking others to explain it to you, consider trying to figure it out yourself, and presenting your thoughts, however vague or seemingly incorrect. Questions here on SO are generally expected to show a little research effort. – jscs Jun 11 '11 at 04:50
  • 1
    possible duplicate of [How to read this kind of pointer in c++?](http://stackoverflow.com/questions/3512692/how-to-read-this-kind-of-pointer-in-c) And, yes. It's tagged [c++], but the answer is the same. – dmckee --- ex-moderator kitten Jun 11 '11 at 19:00

3 Answers3

6

Sc[] is an array of machine instructions, with each byte described in hexadecimal.

The line in main interprets sc as a pointer to a function that takes no arguments and returns a void, and calls the function.

Sherm Pendley
  • 13,556
  • 3
  • 45
  • 57
4

SC is being cast as a function pointer, and then being called. That means that the code in the SC[] is actually machine instructions (encoded in hex).

Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
2
(*(void(*)()) sc)();

Casts sc to a *(void(*)() which is a pointer to a function returning a void and taking no parameters, and calls the function.

trutheality
  • 23,114
  • 6
  • 54
  • 68