C programming: What is the difference between the following pieces of code:\[\small\text{char* string = "The quick brown fox jumps over the lazy dog."}\]\[\small\text{char string[] = "The quick brown fox jumps over the lazy dog."}\]
Well, all I know is that the first one is immutable or something., and that the second one is an array of characters with a '\0' in the end, but I'm sure there are deeper differences, both semantically and at the assembly level.
So, there are a lot of differences here. The first, for example, is a pointer while the second is a concrete array. So, one is allocated in the heap and one is allocated in the stack. Additionally, I'm not entirely sure those assignments are valid, since technically the value for a char* is a memory address, but as I've mentioned before I'm not a regular C programmer.
Actually, those are both valid, both allocated on the stack, and (wait for it).... Both equivalent in C. They are, for all intents and purposes, exactly the same declaration.
There's a slight possibility that assignments to a char[] might get a warning if you try to assign a char* to it, but I don't think so.
I've done the following: char* a = "The quick brown fox jumps over the lazy dog.\n"; char b[] = "The quick brown fox jumps over the lazy dog.\n"; a[2] = '\0'; b[2] = '\0'; fprintf(stdout, "%s%s\n", a, b); And here is the output (note that the first line is a, and the second is b): The quick brown fox jumps over the lazy dog. Th;
oops no semicolon on the second one, but you get the difference :-D
I guess there are subtleties that are only apparent once you look under the hood, at the assembly code.
Actually, the subtlety is in C. Both a[2] and b[2] refer to a memory location 2 * sizeof( char ) after it's respective variable. What's goofing you up is that a refers to the pointer itself, it was never dereferenced: *a[2] ( if that syntax is dead nuts, I'm surprised, but you get the idea ).
@rsmith So *a[2] achieves the intended effect of turning the 3rd character in the sentence into a '\0'? Doesn't work: http://codepad.org/Xc71FImM
I think it will be *(a + 2) that will do it. Alternatively, *(a + 2 * sizeof(char)), but as I recall the C compiler sees pointer math and does the sizeof multiplication. May be wrong about that though.
I thought a[2] was syntactic sugar for *(a + 2), so it wouldn't work anyway :-P http://codepad.org/VHMfbD7q *(a + 2 * sizeof(char)) doesn't work either, since sizeof(char) is 1 byte :-P http://codepad.org/YRAbhoSy
I'm surprised it even compiled. *a[2] was just a conceptual description. The upshot is that a[2] would be 2 * sizeof(char) bytes after where the pointer was stored, as opposed to 2 * sizeof(char) bytes after where the pointer pointed to, which would (if the pointer is properly initialized), b[0].
Join our real-time social learning platform and learn together with your friends!