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

It's unfortunate the author put the arrays-are-pointers thing so early in the doc, as that's a very beginner-to-C mixup and really nothing at all to do with strings. Otherwise, yep. It's pretty bad. C is a great language, but its string handling is definitely garbage. You get used to it pretty quick, and it's not hard to write a handful of sane wrappers or a simple string library for your own use, but the standard library's terrible string functions are an unending source of bugs.


This is almost a cliche among many C language lawyers and/or Stack Overflow answer-rich people and I know you mean well, but: arrays are not pointers.

In some contexts, the name of an array decays to a pointer to its first element. That is a better way of putting it, and it's a (much) weaker statement.

Edit: if they were the same, this code:

    int foo[] = {1, 2, 3};
    int *bar = foo;
    printf("%zu and %zu\n", sizeof foo, sizeof bar);
Would print the same valde twice, but it doesn't. On Ideone [1] I got 12 and 8.

[1]: https://ideone.com/CP7WTu


This also makes a big difference once we start talking about pointers to arrays.

    int a[] = {1, 2, 3}
    int (*p1)[3] = &a; // ok
    int (*p2)[3] = &a[0]; // not ok
    int *p3 = &a; // not ok
(It should be noted that these will compile with warnings in C due to implicit conversions via void*, but you're still risking UB if you actually use the resulting value. They are all errors in C++ because it doesn't have implicit conversion from void*.)


Nothing wrong with your third line. Did you mean something else?


I forgot the &; comment updated now, and I added another example.


Got it, thanks!


I don't see any mention or insinuations of arrays-are-pointers anywhere in the article. Am I missing something?


This bit:

    But you might be asking. “Why can’t I just assign the source variable directly to the destination variable?”

    int main() {
      char source[] = "Hello, world!";
      char* destination = source;
    
      strcpy(destination, source); // Copy the source string to the destination string
    
      printf("Source: %s\n", source);
      printf("Destination: %s\n", destination);
    
      return 0;
    }
    You can. It’s just that destination now becomes a char* and exists as a pointer to the source character array. If that isn’t what you want them this will almost certainly cause issues.




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

Search: