sizeof question

This is a discussion on sizeof question within the C Programming forums, part of the General Programming Boards category; OK I have this next program which asks exactly this: Use the expression sizeof(a) / sizeof(a[0]) (or a macro with ...

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    49

    sizeof question

    OK I have this next program which asks exactly this:
    Use the expression sizeof(a) / sizeof(a[0]) (or a macro with this value) for the array length.

    I came up w/ this code, however my logic tells me I am not using it correctly. Because whatever number I put in for N is the array size. It compiles fine though. Any advice?

    CJ

    Code:
    #include <stdio.h>
    #define N 10
    #define SIZE (sizeof(a) / sizeof(a[0]))
    
    main ()
    {
    	int a[N], i = 0;
    
    	printf("Enter numbers: ");
    	for (i = 0; i < SIZE; i++)
    		scanf("%d", &a[i]);
    
    	printf("In reverse order:");
    	for (i = SIZE - 1; i >= 0; i--)
    		printf(" %d", a[i]);
    	printf("\n");
    
    	return 0;
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You're taking the total byte size of the array and dividing by the 'sizeof' the type of variable that the array is.

    Example:
    Code:
    int array[10];
    Assuming that an int is four bytes, sizeof(array) gives you 40. You divide this by the size of an intenger (4), giving you 10. Thus, the total expression is telling you how many members the array has.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read from 15-pin port
    By C_ntua in forum C Programming
    Replies: 23
    Last Post: 07-11-2008, 09:09 AM
  2. sizeof union question
    By noops in forum C Programming
    Replies: 13
    Last Post: 06-06-2008, 11:56 AM
  3. Design layer question
    By mdoland in forum C# Programming
    Replies: 0
    Last Post: 10-19-2007, 04:22 AM
  4. Malloc,calloc..Sscanf.
    By ozumsafa in forum C Programming
    Replies: 22
    Last Post: 07-26-2007, 01:09 AM
  5. sizeof() EZ question
    By V1P3R V3N0M in forum Windows Programming
    Replies: 15
    Last Post: 01-11-2003, 10:25 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21