News for hackers. Stuff that matters.
Re:Stress impairs cognitive functions - The loss of those fu... by alxv on Monday December 10, 2007 @12:31AM (#87650)
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.
Re:Stress impairs cognitive functions - The loss of those fu... by queensnake on Saturday January 12, 2008 @07:56PM (#97705)
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?
Re:Stress impairs cognitive functions - The loss of those fu... by alxv on Saturday January 12, 2008 @09:31PM (#97726)
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.

Re:Stress impairs cognitive functions - The loss of those fu... by schtog on Sunday October 12, 2008 @03:03PM (#330441)
which is the same as *(n + A)?