0

I am learning c programming with previous Java experience.I have been playing with the following code snippet.

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

#define N 5


int d[7];

void fcn(int b[]) {
  printf("%d\n", sizeof b/sizeof b[0]);
  printf("%d\n", sizeof d/sizeof d[0]);
}

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

  int a[] = { 5, 6, 7, 8, 9 };
  int *b;
  int c[10];
  char cmd[20] = "hello";
  char cmd2[20];
  strcpy(cmd2, cmd);
  printf("%d\n", sizeof a);
  printf("%d\n", sizeof cmd);
  printf("%d\n", sizeof a/sizeof a[0] );
  fcn(a);
  fcn(d);
  b = a;
  //b++;b--;b--;

  //  b = 3;
  *(b+1) = 3;

  printf("N %d %d %d\n", sizeof b/sizeof b[0], *(b + 1), b[1] );
}

Output:

20
20
5
1
7
1
7
N 1 3 3

However, when I call printf("%d\n", sizeof a/sizeof a[0] ); inside main method that gives me 5 as expected but when I give it in the void fcn(int b[]) function parameter it gives me 1 for the same operation.Why?Also I'm not understanding why *(b + 1) printing out 1 and b[1] printing out 3. Since I said b = a;, shouldn't it give me a[1] when I said b[1], i.e. 6?

  • 1
    `*(b + 1)` is not really printing out 1. And you are not printing `b[1]` anywhere. Check your `printf` format string more carefully. Count the format specifiers and count the arguments. See the problem? – AnT Jul 27 '16 at 01:56
  • So sizeof b/sizeof b[0] is printing out 1 since b is a pointer? –  Jul 27 '16 at 02:05
  • Yes, precisely. On your platform size of pointer divided by size of `int` happens to produce 1. – AnT Jul 27 '16 at 02:05
  • 1
    Also, don't use `%d` to `printf` values of type `size_t`. The proper format is `%zu`, not `%d`. – AnT Jul 27 '16 at 02:07
  • b[1] is printing out 3.Why? I said *(b+1)= 3 and b= a.I just tested. –  Jul 27 '16 at 02:08
  • Um... `b[1]` and `*(b+1)` are the same thing. If you did `*(b+1)= 3`, then `b[1]` *should* be `3`. Why do you find it surprising? – AnT Jul 27 '16 at 02:09
  • I see it now, sorry. –  Jul 27 '16 at 02:12

0 Answers0