Thread: array size?

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    913

    array size?

    how can you figure out the size allocated for a array, how much can safely be put in it?

    i mean i do something like

    char temp[255];
    strcpy(temp, "test");
    printf("Array temp is %i chars long", strlen(temp));

    gives 4, but its really 255(well, 254), how can i get 255?

    testing for a seg fault just seems horible.

  2. #2

  3. #3
    Registered User
    Join Date
    Jul 2002
    Posts
    913
    so can it be done if the size isnt known(not compiled with that particular size)?

  4. #4
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by Salem
    > sizeof( temp )
    Beware that this only works when the array itself is in scope.

    Pass the array to a function and all you will ever get is the size of the pointer to the start of the array
    Only if you are passing the the address of the first element. If you pass the address of the array, you can still use sizeof to get the proper size (you'd do sizeof( *temp ) ).

    so can it be done if the size isnt known(not compiled with that particular size)?
    you mean, for instance, if you dynamically allocated it? Nope, there is no standard way in C to get the size of the array. You'd have to just store the size to a variable when you allocate it.

  5. #5
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    Originally posted by Salem
    What are you on about poly?
    Code:
    void fn2 ( char (*a)[10] ) {
        printf( "%d\n", sizeof(a) );
        printf( "%d\n\n", sizeof(*a) );
    }
    ^ was what I was refering too.


    I know it's silly because, of course, you can only pass arrays of length 10 to it. The only reason I mentioned it was because his original example was also silly. He showed the declaration meaning he knew the size at compile-time, just like the above example.

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