15 ms·
A convenient untruth: Array notation in C is a lie
- anjc 10y agoIt's not that convenient an untruth seeing as these are probably some of the first things you learn in C, and some of the first gotchas that'll getcha. Having said that, the article was well written.
- bluetomcat 10y agoSome of the first things that people learn in C is the fallacy that "arrays and pointers are equivalent". An array is a series of contiguously laid-out objects that has a size known at compile time (except C99 VLAs). A pointer, on the other hand is merely a "single cell" that is supposed to contain an address and can be added/subtracted to, also dereferenced. The truth is that array names decay to pointers except when the array is an operand to the `sizeof` or `&` operator.
- jandrese 10y agoRight, the fact that arrays aren't pointers is academic when they decay to pointers at the drop of a hat. In fact it's so easy to decay the array to a pointer that it is generally best to always treat it as a pointer lest you get burned later on during a code refactor. This mostly means never using sizeof() to get the size of an array.
- bluetomcat 10y agoEven if we simplify it this way, arrays are still different because they cannot be assigned to and their decayed pointer can never be NULL (they always have a backing storage provided by the compiler): int arr[5]; int *ptr; // "arr" has a fixed backing storage of sizeof(int) * 5 bytes // "ptr" may point to anything or be NULL, depending on control flow
- jandrese 10y agoBest to check for NULL anyway though, because anything can happen once you let it decay to a pointer. Never assigning them is a good idea though, maybe it's best to think of them as constant pointers? But that's more confusing terminology for a C programmer, so maybe not. People get really wrapped around the axle when differentiating a constant pointer from a pointer to a constant.
- baydonFlyer 10y agoI wish that was the case, as in the "first things you learn in C" unfortunately in most cases I come across it's not and many C programmers maybe know that very basics (int* ptr = arr;) but not much beyond that.
- grymoire1 10y agoI think it's more likely the reaction to someone who uses magic languages that perform complicated actions over a simple assignment. If you think of C as a high-level assembly language whose assignment instruction is converted into a single machine instruction, this type of behavior is not so surprising.
- kbp 10y ago> I think it's more likely the reaction to someone who uses magic languages that perform complicated actions over a simple assignment. If you think of C as a high-level assembly language whose assignment instruction is converted into a single machine instruction, this type of behavior is not so surprising. C assignment isn't that simple. Consider this program: #include <stdio.h> struct point { int x; int y; }; int main(void) { struct point p1 = { 0, 0 }; struct point p2 = p1; ++p2.x; printf("(%d, %d), (%d, %d)\n", p1.x, p1.y, p2.x, p2.y); } It prints "(0, 0), (1, 0)", as most people would expect. C isn't as transparent a layer over assembler as some people like to imagine; it just doesn't have first class arrays.
- TillE 10y agoThat's just doing a copy of contiguous memory though? Sure, C has simple custom data types. I like to think of it as one small step above assembly languages; it's certainly not a "portable assembly", but it's about as low as a high-level language can possibly be.
- kbp 10y agoYes, C is definitely a low-level language, I was just responding to someone's inaccurate justification for why you can't copy arrays like that.
- Vanit 10y agoI don't know how this is a lie or untruth, even in jest. In a language that exposes memory management directly of course you can manually traverse an array.
- allemagne 10y agoIt's just a different way of looking at C that might resonate with someone new to the language and the idea of exposed memory. There's no "lying" but by framing it like a story or an evil conspiracy it might make it interesting or fun enough to stick when a clinical description might not for many students.
- hardlianotion 10y agoIs this article a sign that C has fallen out of mainstream use?
- pjc50 10y agoWhat is "mainstream" these days?
- jcoffland 10y agoWhatever language you use.
- mannykannot 10y agoWhatever language I use.
- logicallee 10y agoReact (a javascript library, sometimes referred to as reactJS or react.js) and more specifically its most popular module, Reagent, which is a full, lazily-loaded preemptive operating system that can run concurrent Java, Pythonjs, Rubyjs programs all from your browser while allowing cooperative suspend, load and save to network or local storage, intertab cooperative process management, etc. Basically, if you're not working in an add-on to a framework library written in javascript running in a web browser, you might as well be using punch cards. /s I made the part about Reagent up, but you know you believed it. We're so far from the metal we might as well be sending a telegram with our requirements. In the five seconds it takes this crap to load and show you a still loading page, your CPU cores have done 40,000,000,000 sixty-four bit operations.
- greenshackle2 10y agoYou laugh, but Odoo* 's hand-rolled, Backbone.js-based frontend framework includes an interpreter for a subset of Python. They call it py.js. I'm not fucking with you. https://github.com/odoo/odoo/tree/10.0/addons/web/static/lib/py.js https://github.com/odoo/odoo/tree/10.0/addons/web/static/lib... Just so that you can experience the full horror: Yes, the Python server ships XML templates with raw embedded Python code to the client. The client then parses the XML and interprets the Python using this py.js thing. If the embedded Python needs to access the database (and it almost always does), the client makes calls to a JSONRPC interface on the server. (If you ever think of using Odoo. Don't. Just... don't.) *An open source ERP.
- jcoffland 10y agoI suppose this article is tongue-in-cheek but it doesn't really demonstrate lies in the C language. It does point out some of the quirks of arrays in C but not calling them real arrays is a matter of interpretation of terms. C defined what the term array meant for a lot of the languages that followed it. That today's languages have diverged from C's definition of array is not surprising.
- burntsushi 10y agoFrom the OP: > Of course, if you’ve read this far you’ll (hopefully) realise that this post should have been taken in jest. Arrays aren’t really a lie (any more than any of C’s constructs are). Despite all the ‘trickery’ C’s arrays work well for many, many programming tasks. They are – as the title of this article suggests – a very convenient set of untruths.
- spacelizard 10y agoBrings back fond memories of the first time I learned C, when I really had to dig into what the difference was between storage durations (auto/stack, dynamic/heap, static, thread local). It makes it increasingly important to think about when an object is going to be stored, and for how long. To me this is still a really useful concept that most high-level languages seem to have all disregarded in favor of extremely eager GC or refcounting, with the exception of Rust.
- bluetomcat 10y agoC has a really simple model with regard to storage durations, but the usage/omission of the respective keywords (static, extern, auto) is what makes it hard for beginners, IMO. `static` means different things at file scope and at block scope, `extern` is redundant most of the time (except when linking to an object from another unit), `auto` is 100% redundant and is a leftover from the days when `int` was implied for every declaration.
- logicallee 10y ago>Brings back fond memories of the first time I learned C, when I really had to dig into what the difference was between storage durations (auto/stack, dynamic/heap, static, thread local) If those are your fond memories, I'd hate to hear your traumatic ones. :P
- cmollis 10y agothe twist with gc or refcounting is that you actually still need to think about memory management.. in many ways, unfortunately, it becomes harder to control. An advantage of user managed memory is that you always need to think about it, with every line you write so if there is an issue, it will become apparent rather quickly. Buffer overruns, however, are never much fun.. and largely avoided with auto memory management so it's clearly useful in most cases. At least with most of boring software that I write.
- valarauca1 10y agomost high-level languages seem to have all disregarded in favor of extremely eager GC or refcounting, with the exception of Rust. Because Rust does a good job of hiding the fact it isn't a high level language. Sure you have ML type checking, pointer safety rules, multiple returns. But if you can see past the syntax sugar you realize it is just C (with guardrails).
- MichaelBurge 10y agoI'd be careful about assuming that C code run on a human interpreter behaves similarly to C code compiled by a modern compiler. For example, string literals probably don't actually have to exist in memory anywhere, but could arise implicitly from the control flow of your program. A compiler could probably turn: char *x = "abcdefghijklmnopqrstuvwxyz" printf("%s", x) into something like: for (int x = 'a'; x <= 'z'; x++) { putc(x); } Maybe when your program thinks it's accessing the 42nd element of that array, it's actually accessing some function of (the number of clock cycles in the CPU's counter, n unrelated code segments XOR'ing into a memory location, the executable's exact binary output) and the compiler has conspired to make these calculate to what that string's value would've been in an imaginary virtual machine to save 2 bytes(or because they're cached). Sounds like a good DRM scheme actually. And who says pointers are to RAM addresses? Maybe the compiler statically notices that the pointer's target stays strictly between 'a' and 'z', and decides to use a simple 26-value counter. Depending on how you debug a program compiled by a sufficiently smart compiler, pointers could point to RAM addresses only when you're looking at them. That for loop you thought you wrote? Well, your program accesses different parts of the result at different times, so it scattered it all over your program so it's lazily computed. The loop counter or pointer never actually exists or takes on any value. You can't be sure any of it exists unless you add logging or inspection. The whole program could be a lie, cleverly calculated to mimic the one you really intended.
- dom0 10y ago> The whole program could be a lie, cleverly calculated to mimic the one you really intended. The standard has a similarly convoluted way of saying that, in a nutshell, C compilers are permitted all optimizations under the as-if rule. (§ 5.1.2.3)
- bluetomcat 10y agoThe "canonical" mental memory model of C (globals in data/BSS, locals on the stack, memory is a big array, code and data are the only artifacts) may be utterly useless when reasoning about the performance of a program, but helps the programmer greatly when approaching a problem. The language was designed with these things in mind, no matter how much more sophisticated compilers and hardware have become, and no matter how much language lawyer fetishists frown on you for saying "this is on the stack" instead of "this has automatic storage duration".
- ordu 10y agoThese facts is not a lies. They are inconviniences which one can see looking on C from perspective of higher level language. But if you learn how to program with assembler before studing C, than all these facts would look like obvious and convinient syntactic sugar. Maybe in C++ these facts become inconvinient, because of C++ pretending to be higher level language than crossplatform assembler. But if it is a problem, it is not problem of C, it is problem of C++.
- gpderetta 10y agoNone of those 'lies' have anything to do with assembler. C deviated from regularity for the sake of convenience in some cases, and now we are stuck with those bad decisions forever.
- ordu 10y ago> None of those 'lies' have anything to do with assembler. They do. Lets take a look at the very first one. "Array name is just a pointer". Assebler "array" is a name of a label. So its just named address in memory. Or we can alternatively say, that assembler array is constant pointer. `sizeof' returns size of array in bytes? Hmm... maybe that because main C abstraction for memory is the assembler one: memory is a continuous sequence of bytes? `sizeof' meant to be used for functions like malloc or memcpy, not for operator `new'. When we use some dynamic memory allocation in assembler we get pointer to untyped memory chunk, compare with C: void* malloc(size_t size); If you wish I can show you the connections of other 'C lies' with assembler abstractions. I'm too lazy to write about all of them, but I could write about one more if you ask. Just pick one you like more. > now we are stuck with those bad decisions forever Yes, you are right. We stuck with that. And it is bad. But it doesn't make my point wrong. C is crossplatform assembler, and these decisions looks pretty good from perspective of assembler. They give to programmer low level control on generated machine code while keeping code portable, and its very useful in some cases. For example when you developing an OS kernel.
- gpderetta 10y agoFrom an assembler point of view a structure of N elements of type T and an array of T[N] have exactly the same layout and are accessed in exactly the same way [1], but in C have wildly different semantics. Sizeof behaves exactly the same way for structs and arrays, so it is one of the few things in C that treat arrays "correctly". [1] although usually the offset is constant for a struct field access.
- cessor 10y agoThe equivalent in C# always made more sense to me (not comparing memory or allocation model between the languages, but simply syntax in relation to a person reading it): int[] arr = new int[5]; // C# int arr[5]; // C The fact that the brackets go on the datatype always made more sense to me, after all, I want to refer to memory of a certain cell size (as indicated by int). I realize that there is a lot of stuff going on when using new, but i believe even in C it should read, because you effectively change the datatype (to be of type pointer, rather than int). int[5] arr; But then, I will now duck and get the hell out. This is the same reason why it feels wrong to write: int *arr; You're not changing the identifier, you're trying to change the datatype. In summary, I believe that the syntax to fiddling with pointers in C is very misleading, and this I fully agree with the article, but as many people are accustomed to this notation, I will now duck and get far away from the internet, in fear of all the hateful comments explaining to me how I am wrong, and apparently just don't understand the superior beauty of complicated C syntax. I will now go and check my garbage collected privilege.
- bluetomcat 10y ago> I will now duck and get far away from the internet, in fear of all the hateful comments explaining to me how I am wrong, and apparently just don't understand the superior beauty of complicated C syntax. I am going to be that person :-) One phrase – "declarations mirror use". In a declaration, you use the same set of operators around the declared object that you would use in a normal expression. All of these operators (asterisk, `[]` and `()`) have the exact same precedence and associativity as in the rest of the language. The type specifier(s) on the left is the final type of the expression that you get after applying all of the operators in the correct order as per the precedence/associativity rules. So when you see: char *arr[X] You identify the identifier first: `arr`. Then, because `[]` takes precedence over the asterisk, you say that `arr` is an array (of size X) of pointers to `char`. In other words, the expression `*arr[some_index]` is of type `char`.
- mannykannot 10y agoTo be fair, while declaration mirrors use, the use contains a few traps for the beginner. If you have written some assembler, you will see where C is coming from. It just occurred to me that most early C programmers were probably proficient In assembly.
- rossy 10y agoThis gets weird when you compare it to how structs work in C. Both are complex data types, so I sometimes forget that array semantics are totally different to struct/union semantics. Unlike arrays, in ANSI C, structs are real value types. You can pass them by-value to functions, return them by-value from functions and assign them by-value to variables of the same type. Also, structs never work like pointers to themselves. You have to dereference the pointer or use the -> syntactic sugar to access a member of a pointer to a struct. Value type semantics enable some neat things, for example, you can zero all the members of a struct by assigning a compound literal to it. You can also make simple structs, like three uint8_ts for an RGB colour, and use them just like they were primitive types. In comparison, it seems almost archaic that you have to break out memset() and memcpy() to zero and move arrays.
- mojuba 10y agoWorth noting that you can always wrap an array in a structure and kick it around in your program happily, as if it's how the language should've been. struct { int a[5]; } arr5 = {{4, 3, 2}}; What's a bit weird though, is that while initialization like above is possible, assignment of a contsant is not as smooth in C, you will have to typedef your structure and use it in a typecast expression: typedef struct { int a[5]; } Array5; ... arr5 = (Array5){{4, 3, 2}};
- gpderetta 10y agoYou can actually drop the extra brackets (at least in C++, but IIRC also in C). C++11 has array<T, size_t> which has proper value semantics. It is implemented exactly like your structure above, so no overhead, and also has a proper operator== and assignment via initializer list.
- ScottBurson 10y agoYes, and there's another inconsistency here as well. Arrays and pointers into arrays are accessed with the same syntax: char a[3], *pa = a; ... a[0] ... pa[0] ... In contrast, with a struct, you have to know which one you have and use the correct operator: struct { int x; } s, *ps = &s; ... s.x ... ps->x ... To be consistent, they could either have made '.' work in both cases, or forced you to write things like '(*pa)[0]'.
- misnome 10y agoE.g. Clickbait.
- 0xffff2 10y agoI.e., not e.g. If you're going to leave snarky two word replies, you should at least use the right abbreviation.
- dang 10y agoWe detached this subthread from https://news.ycombinator.com/item?id=13236850 https://news.ycombinator.com/item?id=13236850 and marked it off-topic.
- misnome 10y agoWhat part of "Array notation in C is a lie".... (End of article "p.s. It isn't") isn't an exact example of clickbait?
- Radle 10y agoSo the only difference between an Array and an *int is how sizeof() behaves? And how do I pass my Array to a function without losing sight of its size?
- JoeAltmaier 10y agoI don't believe that's possible. Except 'by hand'; pass the size as a separate parameter.
- optymizer 10y agoShort answer: For the user? yes. For the type system? no. To keep track of the length of the array, you can pass the number of elements as a second parameter to the function. Long answer: For arrays with a declared length, the length is included in its type (6.2.5.20, page 42, [1]). Therefore, the type of "int a[5]" is "array of 5 integers". The type of "int*" is "pointer to integer". For arrays without a length, the type is considered 'incomplete' (6.2.5.22). So the C typing system considers these 2 different types. "Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue." (6.3.2.1.3) sizeof is essentially an exception. "The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer." (6.5.3.4.2) And that's how sizeof is defined. Because it uses the type to compute the size, and the type of arrays include their length, and the type of arrays doesn't change in sizeof expressions, sizeof will return the total number of bytes of all the elements of the array. [1] C11 standard (draft): http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf
- shultays 10y agoCheck this one out https://news.ycombinator.com/reply?id=13237674 https://news.ycombinator.com/reply?id=13237674
- rhinoceraptor 10y agoBut this is exactly what the index operator is doing. When you write (for example) arr[0] The compiler is re-writing your code as: *(arr + 0) Since addition is commutative, you can also write arr[0] as 0[arr].
- bonoboTP 10y agoYes, it's in the article.
- zwieback 10y agoDon't even get me started on packing when you have arrays of structs...
- utopcell 10y agoC now has static array indices. For example void func(int arr[static 8]) {} imposes a limit on the size of the array that can be passed as an argument (you cannot pass an array of 7 or fewer elements.) I'd suggest that to the author, but given the article, I fear it may give him a heart attack.
- sdegutis 10y agoWhat version of C is this in? And do modern implementations (clang, GCC) adhere to it (without extensions)?
- utopcell 10y agoIt is C99 so it has been part of the language for a very long time
- Vindicis 10y agoJust to add, from the N1256 draft of C99, 6.7.5.3: A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to type’’, where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation. If the keyword static also appears within the [ and ] of the array type derivation, then for each call to the function, the value of the corresponding actual argument shall provide access to the first element of an array with at least as many elements as specified by the size expression.
- FreeFull 10y agoIt's a feature added in C99. Both clang and GCC do support it, assuming -std=c99 or later
- ThatGeoGuy 10y agoI know they're called static array indices, and they're called that because of the use of the keyword `static`, but they don't have to be compile time constant at all (and checks aren't performed at compile time, IIRC). You can have the following: void foo(size_t len, int arr[static len]); Which is really useful in asserting that you won't pass in the null pointer at runtime (so you can remove any `if (arr) {}` checks). Taken further, this exact method is what makes the restrict keyword usable in practice. One of the main problems of the restrict keyword is that you shouldn't be aliasing pointers. By ensuring that your passed-in array isn't actually a null pointer using the above syntax, you avoid one of the biggest problems of aliasing: passing in two null pointers. Consider: void foo1(size_t len1, restrict int* arr1, size_t len2, restrict int* arr2); vs void foo2(size_t len1, restrict int arr1[static len1], size_t len2, restrict int arr2[static len2]); The second is more verbose, but you have a stronger guarantee that this procedure won't be called with pointers aliased to NULL. The compiler can (and I believe in the case of GCC, will) take advantage of this.
- jibsen 10y agoRegarding #3, it's worth noting that even though the elements of the two-dimensional array form a contiguous block of integers, you cannot treat them as such [1]. [1]: http://c-faq.com/aryptr/ary2dfunc2.html http://c-faq.com/aryptr/ary2dfunc2.html
- yCloser 10y agoThis stuff is all taught in 1st year of C.S. I hope that anyone who works with asm, C (and also C++) learned all this when he was still a kid
- ehntoo 10y agoFrom my own experience and what I've seen from major US universities, this does not seem to be the case. For intro (1st year-ish) CS, it looks like most places are teaching Python and C++, with some institutions (such as my own) using Java. An ACM article from 2014 actually has some numbers here. [0] I graduated relatively recently with a bachelors degree, majoring in CS and Computer Engineering. I had only one course which actually used C, and that wasn't for my CS major. I've spent a fair amount of time since then doing low-level work on ARM micros, but definitely wasn't taught this in school. [0] http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the...
- wbkang 10y agoIn the last example, > char string[] = "Hello world"; I thought that gives out warning these days. Isn't the proper type of a string literal the following? > const char string[] = "Hello world"; Therefore, you can't really modify individual characters there.
- smitherfield 10y agoC string literals are " char * ". C++ string literals are " const char * " (one of the minor incompatibilities between the languages). They ought to be "const char[]" but aren't. And, the behavior of "char[]" should be the same as "struct { char[] }", but it isn't.
- gpderetta 10y agoThey actually are proper arrays in C++ [1], although, as usual, they decay to pointers faster than an unstable particle. [1]: https://godbolt.org/g/ZWISCu https://godbolt.org/g/ZWISCu
- smitherfield 10y agoI stand corrected!
- kbp 10y agoYou're confusing things a little bit. 'char s[] = "foo"' is equivalent to 'char s[] = { 'f', 'o', 'o', '\0' }' and gives you a normal mutable array (or you can make it const and then it's const; no surprises); it is okay to mutate that array. 'char * s = "foo"' gives you a pointer to a string literal that might be placed in read-only storage; in C++ it is a const char * (so modern compilers should complain about that initialisation), while in C it is a char * where it's UB if you modify it (compilers may warn about storing it in a non-const char *; many don't).
- coldpie 10y ago> Isn't the proper type of a string literal the following? No, it's a const char pointer. Your declaration actually makes a copy of the "Hello world" string into a new char array, distinct from the string literal itself: [~]$ cat test.c #include <stdio.h> int main(int argc, char ** argv) { char a[] = "test2"; printf("sizeof(a): %lu\n", sizeof(a)); return 0; } [~]$ gcc -std=c99 -pedantic -Wall -o test test.c [~]$ ./test sizeof(a): 6 [~]$
- notacoward 10y agoWorth noting: since everyone on HN is clearly an expert on C[1], we're just as clearly not the audience for this post. It's obviously written for people who haven't learned this yet, who might still be fooled by the superficial similarity of arrays in C to arrays elsewhere (or to what any rational non-lazy person not implementing their first compiler might expect). That doesn't make it a bad article, so stop being so gratuitously negative. It's actually a pretty good explanation, for somebody at that level, of how C arrays can trip you up. I might use it myself, as a reference for some of the people I mentor. Pedagogy matters. [1] Or any other topic. Just ask any one of us. Apparently we all sprang fully formed from Athena's brow, already endowed with every bit of knowledge we'll ever need.
- pdog 10y agoWhy did people think otherwise? Chapter 5 of K&R[1] is titled Pointers and Arrays and basically explains that arrays and pointers are equivalent. [1]: https://www.amazon.com/Programming-Language-Brian-W-Kernighan/dp/0131103628/ https://www.amazon.com/Programming-Language-Brian-W-Kernigha...
- deleted 10y ago[deleted]
- notacoward 10y agoThe point of the article is that sometimes they're not equivalent, and that creates a lot of confusion. Please read it before commenting on it.
- ams6110 10y agoI thought the same things as GP. Anyone who has read K&R (as any C programmer ought to have) will know everything in this article.
- notacoward 10y agoI don't think that's true. While I don't have my copy of K&R handy, I don't recall it covering all the subtleties of how assignment and increment operators and sizeof will work differently for something declared as an array vs. something declared as a pointer. At least in the edition I've had, it just had the same "pointers and arrays are equivalent" which is misleading in exactly the way this article describes. Did that get added in your much-later edition?
- mwfunk 10y agoI'd go so far as to say that any C programmer at all (whether or not they've read K&R) will know everything in this article. However, it's probably interesting or useful for people who are either in the process of learning C, or people who have to read and write it occasionally, but never truly learned the language. These are definitely all pain points for people coming to C from higher-level languages.
- coldpie 10y agoThe thing to keep in mind is Never (Never) use array syntax in your function arguments. It implies something that you can't rely on. More on this: https://lkml.org/lkml/2015/9/3/428 https://lkml.org/lkml/2015/9/3/428
- ThatGeoGuy 10y agoSee https://news.ycombinator.com/item?id=13237674 https://news.ycombinator.com/item?id=13237674 and my corresponding reply, where you _should_ use array syntax for function arguments, but you need to do it using the `static` index syntax.
- pklausler 10y agoIf you want Pascal, you know where to find it. C is C.
- valbaca 10y agoThis is covered in "Expert C Programming: Deep C Secrets" https://www.amazon.com/gp/product/0131774298 https://www.amazon.com/gp/product/0131774298
- tlan 10y agoThe mycodeschool channel on youtube has a playlist[1] that provides a great visual explanation of this information. I found it really useful in getting my head around these concepts. [1]: https://www.youtube.com/playlist?list=PL2_aWCzGMAwLZp6LMUKI3cc7pgGsasm2_ https://www.youtube.com/playlist?list=PL2_aWCzGMAwLZp6LMUKI3...
- Animats 10y agoI once proposed a backwards-compatible way out of this: "Safe Arrays for C"[1]. The fundamental problem with arrays in C is that compiler has no idea how big they are. My proposal was to replace int read(int fd, char buf[n], size_t n); with a safe form int read(int n; int fd, char (&buf)[n], size_t n); This says that the size of "buf" is "n", which comes in as another parameter. There are no array descriptors; the generated code for a call is the same. Thus, this is backwards-compatible, allowing mixing of "regular C" and "safe C" modules. The programmer has to know how big the array is, after all. There must be some way to compute the array size from other variables or constants, or the program has no hope of working. All C needs is a way to allow the programmer to say that in the language. Then subscript checking is possible. Buffer overflows can be eliminated. The required changes to C are minor. The big one is adding C++ references. Instead of passing a pointer to the first element of an array, you pass a reference to the array. Same object code, but now arrays are first-class objects. This was discussed at length on the C standards digest back in 2012. After many revisions, the conclusion was that it was technically feasible, but too difficult politically. [1] http://www.animats.com/papers/languages/safearraysforc43.pdf http://www.animats.com/papers/languages/safearraysforc43.pdf
- chrisseaton 10y ago> The fundamental problem with arrays in C is that compiler has no idea how big they are Isn't that the compiler's choice, to not know how big they are? You could write a standards compliant implementation of C that did track how big arrays were if you wanted to couldn't you?
- Animats 10y agoThat's been done, with "fat pointers". GCC used to have an option for that, but it wasn't used much. The overhead is all at run time and is substantial.[1] [1] http://www.imperial.ac.uk/pls/portallive/docs/1/18619746.PDF http://www.imperial.ac.uk/pls/portallive/docs/1/18619746.PDF
- MaulingMonkey 10y ago> Why is this failing? Because the array’s name is a lie! Using a variable as an expression normally yields its value, but in the case of arrays the array name yields a pointer (to the first element; which is at least reasonable) Ahh, not quite. sizeof(array) was using the variable as an expression - not an evaluated expression, but an expression nonetheless - and it's clearly not giving us the same result as sizeof(array+0). In C++, you can even construct references, which can be abused in conjunction with templates to create a 'safe' array size check, which relies on array maintaining it's array typing: int (&r)[5] = array; Now, arrays are implicitly convert to pointers is you so much as sneeze in the same room as them, but there are instances (namely arrays of arrays and the like) where you can fuck up your pointer math if you assume that simply using the array name yields a pointer, or that the array 'is' a pointer - because that is the lie! If I'm feeling particularly explicit, I'll write something like (assuming a and b are arrays, in C++ again): std::copy(a+0, a+N, b+0); Where the +0s ensure I'm actually dealing with pointers. This avoids any compiler errors from having mixed types for 'a' (array) and 'a+N' (pointer) which, while rare (the former typically converts to a pointer at some point), has happened to me at least once. The real reason "this" (array init and assignment) is failing is that C decided arrays weren't copyable and assignable like this. That's all. Really! Now, one can think of plenty of rationale that made sense at the time (memcpy is more explicit, simplifies the implementation to only implement copy/assignment for simpler types, etc.) but it ultimately boils down to the choice of the implementors.
- kazinator 10y ago> Why is this [array assignment] failing? Because the array’s name is a lie! Using a variable as an expression normally yields its value, but in the case of arrays the array name yields a pointer (to the first element; which is at least reasonable) Sorry, no; the assignment fails because an array isn't a modifiable lvalue. Array assignment simply isn't supported. If array assignment were supported the array-to-pointer conversion ("decay") could be suppressed in that case to make it work. Just like it is suppressed when an array is the operand of sizeof of & (address-of). Assignment of arrays is supported when they are struct/union members: struct wrapper { int a[5]; } x = { 0 }, y = x; We can return this from a function, too.
- joeld42 10y agoI was lucky to learn C with pointers first, and then arrays. When you think about it as just chunks of memory, it all makes sense and is easier to reason about what the cpu will do. This is another example of a "simplifying abstraction" that is more misleading than simplifying.
- leonatan 10y agoThese are no "lies", just misunderstanding on the part of those that believe the untruths. Those that have basic understanding of C know most of the things listed in the article.
- yason 10y agoC has no more real arrays than assembly: for the cpu, it's just differently indexed pointers in the end. But arrays in C have some notable differences from pointers in C however, please read a good detailed description here: http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arrays-equivalent-in-c http://eli.thegreenplace.net/2009/10/21/are-pointers-and-arr...
- GrinningFool 10y agoWell done, Grasshopper. You are now ready to begin the true journey of understanding.