Lectures‎ > ‎

Week01

Some C Code Decoding

Work in groups of 5 to figure out what the following C code outputs. Do not compile/run to figure out.
You can ask yes/no questions of me and the TAs

Program 1:

#include<stdio.h>

int main(int argc, char **argv)
{
    unsigned char a;
    
    a = 0;
    printf("a = %d\n", (int) a);
    
    a = a - 1;
    printf("a = %d\n", (int) a);

    return 0;
}

Program 2:
#include<stdio.h>

struct foo {
    int a;
    int b;
    char c;
    char d;
    char e;
};

int main(int argc, char **argv)
{
    struct foo myfoo;
    int *p;
    int x;
    char *c;
    
    myfoo.a = 1;
    myfoo.b = 2;
    myfoo.c = '1';
    myfoo.d = '2';
    myfoo.e = '\0';
    
    p = &myfoo.a;
    p = p + 1;
    
    x = *p;
    
    printf("x = %d\n", x);
    
    p = p + 1;
    c = (char *) p;
    
    printf("c = %s\n", c);
    
    return 0;
}
Comments