K
[email protected] said:jaysome said:^^^^^^^^^^^^^On 29 Aug 2006 19:06:09 -0700, "(e-mail address removed)" <[email protected]>
wrote in comp.lang.c:
Chad wrote:
Given the following code
string_len = strlen(msg_list[0]);
(void)printf("1st element is %ld char long", string_len);
This of course produces undefined behavior, unless of course size_t is
typedef'ed to unsigned long on your platform.
Don't you mean "signed long" or just plain old "long"? The conversion
specifier for "unsigned long" is "%lu", not "%ld".
I did not cast it knowing that size_t is defined on my box as unsigned
long.
And since I could just see the size of the object, I didn't bother. I
knew it wasn't going to exceed the size of signed long. I was lazy.
The two correct ways to cast this thing would have been:
pre-c99:
printf("%lu", (unsigned long)string_len);
c99:
printf("%zu", string_len);
The odd thing about the pre-c99 cast is that we have to assume a type
for size_t. This is where this argument gets odd. The compiler I use
isn't completely c99 compliant, so I cannot use the c99 example above.
However, it's difficult to argue that size_t will not all ways be
unsigned long because you would have to change your printf typecasts to
make your code portable between architectures.
Chad said:Given the following code
include <stdio.h>
#include <stdlib.h>
int main(void) {
char *msg_list[] = {" apple", " orange", " grape" };
printf("name: %s \n", msg_list[0]);
printf("size: %d \n", sizeof(msg_list));
return 0;
}
I thought taking sizeof(msg_list) would give me the size of the string
"apple" (ie 6). Instead, I get
the following:
name: apple
size: 12
What I'm missing here?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.