-2

i'm following cLearnthehardway at exercise 8 the following code was written , i have 2 questions

  • while printing and integers it used %ld to print them not %d !!
  • while printing areas[10]//out of range it printed 0! why didn't it show me an error while it does by valgrind(6erros)

#include<stdio.h>

int main(int argc,char *argv[])
{

int areas[]={10,12,13,14,20};
char name[]="Zed";
char full_name[]={'Z','e','d',' ','A','.',' ','S','h','a','w','\0'};

printf("The size of an int: %ld\n", sizeof(int));//why didn't we use %d instead of %ld(*)
printf("The size of areas (int[]):%ld\n",sizeof(areas));//*
printf("The number of ints in areas : %ld\n",sizeof(areas)/sizeof(int));//*
printf("The first area is %d, the second area is %d\n",areas[0],areas[1]);//Printed areas[10]=0!!
printf("The size of a char is: %ld\n",sizeof(char));//*
printf("The size of name(char[]) is:%ld\n",sizeof(name));//*
printf("The number of chars is : %ld\n",sizeof(name)/sizeof(char));//*
printf("the size of FULL NAME  (char[]) is:%ld\n",sizeof(full_name));//*
printf("The number of chars in full name is %ld\n",sizeof(full_name)/sizeof(char));//*
printf("name=\"%s\" and full name =\"%s\"\n",name,full_name);// what is \"%s\" \ is an    ESCAPE


return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

2 Answers2

1

Operator sizeof returns value of type size_t. Usually size_t is defined as unsigned long (though it can be any unsigned integral type). According to the C Standard sizeof( long ) is greater than or equal to sizeof( int ). For example sizeof( long ) can be equal to 8 while sizeof( int ) can be equal to 4. So in the code you showed format specifier %ld is used to output an object of type long int though it would be better to use %zu where flag z means that an object of type size_t will be outputed.

As for arrays then the compiler does not check boundaries of arrays. It is the programmer who shall correctly specify indices of array elements.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

About printing sizes: sizeof(int) is of integral type size_t. On some machines that type is the same as unsigned int, on other machines it is the same as unsigned long. In practice the size is a small integer, so you can code

 printf("The size of an int: %d\n", (int) sizeof(int));

Pedantically you could #include <inttypes.h> and use some formats (e.g. %zu) there.

About out-of-range indexes, they cause a buffer overflow at runtime (which may SEGV). This an example of undefined behavior. Always avoid it. Here are examples of horrors which could happen on UB.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547