-1

I would like to understand why this code works:

void open_image(const char *filename)
{
    char *ImageName = filename;
    printf("%s", ImageName);
}

const char image_name[] = "image.jpg";
open_image(image_name);

it prints "image.jpg" as wanted, but I don't know how the program knows the length of the string.

The program knows the size of the string image_name as it is computed during compilation. But in the open_image function, how does the printf function knows the length of this string as it is only given the pointer ImageName created at runtime?

Thank you.

Wheatley
  • 162
  • 1
  • 7
  • 2
    Have you read the chapter on strings in a C tutorial? This will almost certainly be one of the first things it explains. – Barmar Jan 26 '23 at 22:13
  • @Barmar yes, I have forgotten this fundamental property of strings ... – Wheatley Jan 26 '23 at 22:14

1 Answers1

0

In C a string (array of char) is always terminated by the "terminator" character '\0', so you can get the length of the array by checking each character until you find it.

Here's a simple solution:

int i = 0;
char ch;
do
{
  ch = arr[i];
  i++;
} while(ch != '\0');
printf("String length: %d\n", i-1); // This will give the string length
printf("Total length of the array: %d\n", i); // This will give the array full length, including the terminator character.

Probably the best way to get a char array length is to import the string.h library which exposes the strlen() function. However, it's always useful to learn how things actually work at low-level, especially when learning C). :-)

mikyll98
  • 1,195
  • 3
  • 8
  • 29
  • 1
    Entering the loop is dicey when `c` is uninitialised. – Fe2O3 Jan 26 '23 at 22:16
  • 2
    This will never give the size of the array. It can give the length of the string. The edit doesn't improve. – Weather Vane Jan 26 '23 at 22:17
  • 1
    _"including the terminator character"_ - no - and why are you involving a new (uninitialized) variable? `int len; for(len = 0; arr[len] != '\0'; ++len) {}` would be enough. – Ted Lyngmo Jan 26 '23 at 22:22
  • @WeatherVane I got something urgent right while I was replying, that's why I tried to fix it quickly. I edited the post btw... – mikyll98 Jan 26 '23 at 22:29
  • @TedLyngmo you're right, I edited the reply and used a do {}while; but the result should be the same. (Just with one more variable) – mikyll98 Jan 26 '23 at 22:31
  • @mikyll98 The result after the edit is not the same as before. Now it _does_ include the terminator - and you're now not reading `ch` when it has an indeterminate value as before. That's good. – Ted Lyngmo Jan 26 '23 at 22:33
  • 1
    `int` is the wrong type. t should be `size_t` – 0___________ Jan 26 '23 at 22:35