Thread: Define the size of an integer type dynamic array

  1. #1
    Registered User
    Join Date
    Nov 2018
    Posts
    9

    Define the size of an integer type dynamic array

    Hi guys,
    I would like to define the count of an integer array but I got stuck in that. I increased the size of the array dynamically using the possibilities of 'realloc' method.

    May I mess up the number of the array with these reallocation ? Or is it an incorrect usage of 'realloc' ?
    Any help would be appreciated

    You can see my simplified code:
    Code:
    #include<stdio.h>
    int main()
    {
        char myString[16]="cows_cats_chicks"; 
        int c_LetterCounter = 0;     
        int* c_LetterPosArray = (int*)malloc(0);  // the array which stores the positions of the 'c' letters
        
        int index=0;
        for (index=0;index<strlen(myString); index++)
        {
            if (myString[index] == 'c')
            {
                c_LetterCounter++;
                c_LetterPosArray = realloc(c_LetterPosArray, c_LetterCounter*sizeof(int));
                c_LetterPosArray[c_LetterCounter-1] = index;
                printf("The current index of the 'c' letter: %d\n",  c_LetterPosArray[c_LetterCounter-1]);
            }
        }
        
        // just an example, the array isn't empty
        printf("The 2nd position of 'c' letter in the 'cows_cats_chicks' string: %d\n", c_LetterPosArray[1]);
        
        int len = sizeof(c_LetterPosArray) / sizeof(int);
        printf("The size of the integer array: %d\n", len);
        
        int len2 = sizeof(c_LetterPosArray) / sizeof(c_LetterPosArray[0]);
        printf("The size of the integer array with different calculation: %d\n", len2);
        
        getchar();
    }

    But that simple array size definition work very well in static arrays:
    Code:
    int arr[] ={1,2,3,4,3,3,3};
    int len = sizeof(arr) / sizeof(int);
    Very thanks for your help!

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    That doesn't work as expected because you're getting the size of a pointer, not an array.

    Do you really need dynamic memory allocation though?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,667
    The sizeof thing doesn't work on pointers.

    Besides, the length of your malloc'ed array is already stored in c_LetterCounter

    You can start off with
    int* c_LetterPosArray = NULL;
    and realloc will know what to do.
    You don't have to prep with a dummy malloc call.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    One tip abour realloc... Never do things like this:

    Code:
    c_LetterPosArray = realloc(c_LetterPosArray, c_LetterCounter*sizeof(int));
    if realloc fails it will return NULL, but the original buffer won't be deallocated and you'll get a memory leakage. The secure approach should be something like this:

    Code:
    p = realloc( c_LettterPosArray, c_LetterCounter * sizeof(int) );
    if ( p == NULL )
    {
      // error handler...
      free( c_LetterPosArray );
      exit( 1 ); 
    }
    c_LetterPosArray = p;

  5. #5
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Quote Originally Posted by flp1969 View Post
    One tip abour realloc... Never do things like this:

    Code:
    c_LetterPosArray = realloc(c_LetterPosArray, c_LetterCounter*sizeof(int));
    if realloc fails it will return NULL, but the original buffer won't be deallocated and you'll get a memory leakage. The secure approach should be something like this:

    Code:
    p = realloc( c_LettterPosArray, c_LetterCounter * sizeof(int) );
    if ( p == NULL )
    {
      // error handler...
      free( c_LetterPosArray );
      exit( 1 ); 
    }
    c_LetterPosArray = p;
    This forum needs to get the like button back!
    Fact - Beethoven wrote his first symphony in C

  6. #6
    Registered User
    Join Date
    Nov 2018
    Posts
    9
    Hi guys,
    thank you very much for these useful information! Sizeof method doesn't work on pointers. Besides of that thanks for the correction with regards to the safe using of the memory reallocation. I included your suggestions in my code, and i will use that error handling in the future.
    Thanks again!

    Code:
    #include<stdio.h>
    int main()
    {
        char myString[16]="cows_cats_chicks"; 
        int c_LetterCounter = 0;     
        int* c_LetterPosArray = NULL;  // the array which stores the positions of the 'c' letters
        int* p = NULL; // temporary pointer ensuring the security
         
        int index=0;
        for (index=0;index<strlen(myString); index++)
        {
            if (myString[index] == 'c')
            {
                c_LetterCounter++;
                p = realloc(c_LetterPosArray, c_LetterCounter*sizeof(int));
                if (p== NULL)
                {
                	// simple error handling
    				printf("Memory allocation fails!\n");
    				free( c_LetterPosArray );
      				return 0;
    			}
    			c_LetterPosArray = p;						
                c_LetterPosArray[c_LetterCounter-1] = index;
                printf("The current index of the 'c' letter: %d\n",  c_LetterPosArray[c_LetterCounter-1]);
            }
        }     
        getchar();
    }

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    This is problematic:
    Code:
    char myString[16]="cows_cats_chicks";
    As it turns out, the string has a length of 16, which means that you need an array of 17 chars to hold it, including the null character. It would have been better to write:
    Code:
    char myString[]="cows_cats_chicks";
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Nov 2018
    Posts
    9
    Dear laserlight,
    very thanks for the correction.
    The importance of the usage of the terminating zero ( '\0' character), at the char array declaration, is engraving in my mind.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How define array type with 4 elements?
    By barracuda in forum C Programming
    Replies: 8
    Last Post: 01-20-2015, 07:59 AM
  2. Define array size
    By verbod in forum C Programming
    Replies: 3
    Last Post: 01-11-2015, 09:24 PM
  3. Dynamic Array - Size
    By vijay s in forum C Programming
    Replies: 2
    Last Post: 01-17-2012, 11:11 PM
  4. define array size at later stage of program?
    By DavidDobson in forum C Programming
    Replies: 2
    Last Post: 05-04-2008, 03:35 PM
  5. C integer type Size
    By [guard] in forum C Programming
    Replies: 8
    Last Post: 09-26-2002, 03:43 PM

Tags for this Thread