Thread: size of array

  1. #1
    Unregistered
    Guest

    Unhappy size of array

    How i can find the size of array?! for example i have the program below and i want to replace the number 4 with the array size! thanks 4 any help!

    Code:
    #include <stdio.h>
    int main ()
    {
    char str []="MORAL"; int i, j;
    puts ("\n");
    for (i=0; i <= 4; i++)
    {
    for (j=i+1; j <= 4; j++)
    printf ("{%c, %c}\n",str[i],str[j]);
    }
    return 0;
    }

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    > How i can find the size of array?!

    sizeof(str)

    Alternatively, if the string is smaller than the array (which it isn't, in your case), then

    #include <string.h>

    strlen(str);

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    Originally posted by Govtcheez
    Alternatively, if the string is smaller than the array (which it isn't, in your case) ...
    The string is not smaller but strlen doesn't count the null character...

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The size of the array is given by
    sizeof(arr)

    To count the number of valid subscripts of the array, its
    sizeof( arr ) / sizeof( arr[0] )

    I use this macro quite a lot

    #define ASIZE(x) (sizeof(x)/sizeof(x[0]))

    Then I can do
    for ( i = 0 ; i < ASIZE(arr); i++ ) arr[i] = 0;

  5. #5
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    > The string is not smaller but strlen doesn't count the null character...

    Yeah, I think I said that when I said it wasn't, in his case.

    I meant a situation like

    char s[100] = "yo";

    sizeof returns 100 (assuming a 1 byte char), while strlen returns 2.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of array
    By goran00 in forum C Programming
    Replies: 38
    Last Post: 04-02-2008, 09:57 AM
  2. Invalid conversion from 'void*' to 'BYTE' help
    By bikr692002 in forum C++ Programming
    Replies: 9
    Last Post: 02-22-2006, 11:27 AM
  3. Replies: 42
    Last Post: 12-19-2004, 08:59 AM
  4. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  5. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM