char str[]="S\065AB";
printf("\n%d", sizeof(str));

explain the output.
i am getting 5.

Dani AI

Generated

The output 5 is correct. The initializer "S\065AB" contains an octal escape: \065 is octal 65 → decimal 53, which is the ASCII code for the character '5'. The compiled array therefore holds the bytes 'S', '5', 'A', 'B', '\0'. sizeof on that array yields 5 because it reports the total number of bytes in the array (including the terminating NUL).

A few important C details that clarify the behavior:

  • An octal escape consumes up to three octal digits (0–7), so \065 is a single character constant, not a backslash plus digits.
  • sizeof on an array is a compile-time size in bytes; strlen computes the runtime length up to the first '\0' and does not count the terminator. They therefore serve different purposes.
  • Printing sizeof with %d (an int) is incorrect; sizeof yields size_t. Use %zu to print it portably.

Example showing the typical difference between array and pointer (useful for debugging):

#include <stdio.h>
#include <string.h>

int main(void) {
    char arr[] = "abc";
    char *ptr = arr;
    printf("sizeof(arr) = %zu, strlen(arr) = %zu\n", sizeof arr, strlen(arr));
    printf("sizeof(ptr) = %zu\n", sizeof ptr);
    return 0;
}

Notes tied to the thread: is correct about the octal escape producing '5'. ’s suggestion to use strlen applies when the runtime length (excluding the NUL) is needed. ’s caution about embedded '\0' is important—embedded NULs make strlen shorter than the buffer. ’s rule of thumb (strlen normally one less than sizeof for a literal-initialized array) holds in the common case, but watch for pointers, embedded NULs, and printing with the wrong format specifier.

Recommended Answers

All 5 Replies

this is what it means fifth is null terminator 065 in oct is '5' check ascii table

#include <stdio.h>

int main()
{
   char str[]="S\065AB";
   char strSame[5] = { 'S','\065', 'A', 'B', '\0'};

   printf("str 1 %d \n", sizeof(str));
   printf("str 2 %d\n", sizeof(strSame));
   printf("same ? %d [%s] [%s]",strcmp(str, strSame),str, strSame);   

   return 0;
}
commented: nice :) +14

use strlen

strlen find the exact length

use strlen

Maybe, but maybe not. Depends on what you want, strlen() and sizeof() may return different values such as when the buffer contains embedded '\0' characters.

strlen and sizeof should always return different values because strlen never includes the trailing '\0'. In a compleatly normal string such as "Hello World" with no embedded terminators strlen will return a value 1 less than sizeof returns.

It they don't return different values you have a buffer overrun in progress.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.