Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

And if you change your example only slightly, you can break again most-people's mental-model of pointers:

    #include <stdio.h>

    void fn(char *s) {
        printf("[%s]\n", s);
    }

    int main() {
        char *s;
        s = "hello world";

        fn(s);

        return 0;
    }
And yet again:

    #include <stdio.h>

    void fn(int s) {
        printf("[%s]\n", (char *)s);
    }

    int main() {
        char *s;
        s = "hello world";

        fn((int)s);

        return 0;
    }
And back to a single char:

    #include <stdio.h>

    void fn(char *c) {
        printf("[%c]\n", *c);
    }

    int main() {
        char c = 'a';

        fn(&c);

        return 0;
    }
The ugly and evil way:

    #include <stdio.h>

    void fn(char *c) {
        printf("[%c]\n", c);
    }

    int main() {
        int c = 'a';

        fn((char *)c);

        return 0;
    }
And the obvious way:

    #include <stdio.h>

    void fn(char c) {
        printf("[%c]\n", c);
    }

    int main() {
        char c = 'a';

        fn(c);

        return 0;
    }
It is not difficult to see why most people find pointers in C confusing.


This will blow people's mental models of C (genuine example):

    #include <stdio.h>

    int main()
    {
       char const* c = "hello";

       // this is the interesting bit - n[c] == c[n] (n = number literal) !!! I swear, try it.

       printf("This program compiles and prints:'%c %c %c %c %c'\n",
          0[c], 1[c], 2[c], 3[c], 4[c]);
       return 0;
    }

    // See? I read that both forms are translated to *(c + n), 
    // which explains the equivalence. Weird, no?


See? I read that both forms are translated to * (c + n), which explains the equivalence. Weird, no?

Well, that surely is evil, yet perfectly valid C code. But personally, I don't find it surprising. Of course, you need to grok what A[n] really is -- i.e., syntactic sugar for *(A + n), as you just explained.


which is the same as *(n + A)?




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: