C strings and pointers and arrays, revisited…

Previously, I posted more of my “stream of consciousness” ramblings ending this bit of code:

#include <stdio.h>
#include <stdlib.h> // for EXIT_SUCCESS
#include <string.h> // for strlen()

int main()
{
    const char *stringPtr = "hello";
    
    printf ("sizeof(stringPtr) = %ld\n", sizeof(stringPtr));
    printf ("strlen(stringPtr) = %ld\n", strlen(stringPtr));

    printf ("\n");

    const char string[] = "hello";

    printf ("sizeof(string) = %ld\n", sizeof(string));
    printf ("strlen(string) = %ld\n", strlen(string));

    return EXIT_SUCCESS;
}

Sean Patrick Conner commented:

I would expect the following:

sizeof(stringPtr) = 8; /* or 4 or 2, depending upon the pointer size */
strlen(stringPtr) = 5;

sizeof(string) = 6; /* because of the NUL byte at the end */
strlen(string) = 5;

– Sean Patrick Conner

Sean sees things much more clearly than I. When I tried it, I was initially puzzled by the output and had to get my old brain to see the obvious. His comments explain it clearly.

These musings led me to learning about “%zu” for printing a size_t, and a few other things, which I have now posted here in other articles.

I learn so much from folks who take time to post a comment.

More to come…

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.