-1

Can you help me out to understand why I'm getting this output.

#include<stdio.h>
#include<string.h>
void main() {
char a[] = "Hello World";
char *p;
p=a;
printf("%d%d%d%d",sizeof(a),sizeof(p),strlen(a),strlen(p));
}

output: 1281111 (My OS is of 64-bits)

Saying that the above code should have shown 1241111(output) if It is compiled and ran on a 32-bit system. Due to 64-bit It shows 1281111.

In my First year, I saw this question and when I went to look for the output, I get 1281111.

But surprisingly above code's output has two options:1)12121111 and 2)1221111.(University Question).

GAMING INC
  • 53
  • 5
  • 4
    It's a terrible question. Shows that universities still teach implementation details as unwavering truth. – StoryTeller - Unslander Monica May 25 '19 at 17:59
  • 1
    12121111? 96-bits computing? Also, there is `%zu` for `size_t` instead of `%d` which should have emitted a warning. I'd recommend using some spaces or any other separator between each number if you don't want to get confused with where each value starts or ends. – sidyll May 25 '19 at 18:07
  • 1
    Sounds like the question was written for a time when 8 and 16-bit compilers were widespread. ;-) (`12 2 11 11` or `12 1 11 11` would be what you would expect in those cases.) – mpontillo May 25 '19 at 18:21

1 Answers1

1

If you change the printf() statement to the following, it's easier to see what's going on:

printf("%d\n%d\n%d\n%d\n",sizeof(a),sizeof(p),strlen(a),strlen(p));

On my system, this results in the output:

12
8
11
11

In other words:

  • The size of the array is 12 bytes. (11 for the string, plus one for the \0 character.)
  • The size of the pointer is 8 bytes (because I'm using a computer with 64-bit memory addresses, as opposed to a 32-bit computer which would likely output 4).
  • When used as strings (char* pointers), a and p are equivalent. (because p points to a.) The length of the string Hello World is 11 (since strlen() doesn't include the \0 byte at the end of the string).

Hope this helps.

mpontillo
  • 13,559
  • 7
  • 62
  • 90
  • 1
    You **still** cannot print a `size_t` with `%d`! – Antti Haapala -- Слава Україні May 25 '19 at 19:04
  • Yeah, I know it's incorrect. It compiled a warning per `%d`. ;-) It's undefined behavior, yes, but it's likely to print the correct output anyway. See [this question](https://stackoverflow.com/questions/2524611/how-can-one-print-a-size-t-variable-portably-using-the-printf-family) for more details. I don't think there was a standard way to print `size_t` and `ssize_t` with `printf` format strings until C99 was standardized. – mpontillo May 25 '19 at 21:19
  • Cast to `unsigned long` and print with `%lu`, going to work for any conceivable architecture for this program. – Antti Haapala -- Слава Україні May 26 '19 at 04:03