Re:C Strings and my slow descent to madness
by coldpie on Thursday April 06, 2023 @09:26AM
(#35468022)
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.
[ Parent
| on HN ]
Re:C Strings and my slow descent to madness
by gpderetta on Thursday April 06, 2023 @10:21AM
(#35468650)
I don't see any mention or insinuations of arrays-are-pointers anywhere in the article. Am I missing something?
Re:C Strings and my slow descent to madness
by coldpie on Thursday April 06, 2023 @10:38AM
(#35468888)
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.
Re:C Strings and my slow descent to madness
by unwind on Thursday April 06, 2023 @12:52PM
(#35471093)
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.
Re:C Strings and my slow descent to madness
by int_19h on Thursday April 06, 2023 @03:52PM
(#35473497)
This also makes a big difference once we start talking about pointers to arrays.
int a[] = {1, 2, 3}
int (*p)[3] = &a; // ok
int *q = a; // not ok
Re:C Strings and my slow descent to madness
by strkitten on Thursday April 06, 2023 @05:03PM
(#35474405)
Nothing wrong with your third line. Did you mean something else?