Thread: dynamic array

  1. #1
    Registered User
    Join Date
    Feb 2022
    Posts
    73

    dynamic array

    In my code, I am allocating memory for 2 elements first, then assigning value at each memory location. when I print them I get their values.

    then I allocate memoary for more 3 elements then assigning value at each memory location. when I print them I get their values.

    Now I have total five elements which are stoared at five memory location.

    I want to print all the five elements but when i print their value I don't get expected value

    Code:
    #include <stdio.h>
    
     #include <stdlib.h> 
      
    int main() 
    {     
        int i;
      
        // Dynamically allocate memory using malloc() 
          int* ptr = (int*)malloc(2 * sizeof(int)); 
      
        // Check if the memory has been successfully 
        // allocated by malloc or not 
        if (ptr != NULL) 
        { 
            // Memory has been successfully allocated 
            printf("Memory successfully allocated using malloc.\n"); 
      
        // Get the elements of the array 
           for (i = 0; i < 2; i++) 
           { 
               printf("The elements of the array are: ");
               scanf ("%d", ptr + i);            
            } 
      
            // Print the elements of the array 
            printf("The elements of the array are: "); 
            for (i = 0; i < 2; i++) 
            { 
                printf("%d, ", *(ptr  + i)); 
            } 
        } 
     
     
            
        // Dynamically allocate memory using malloc() 
          ptr = (int*)realloc(ptr, 3 * sizeof(int)); 
      
        // Check if the memory has been successfully 
        // allocated by malloc or not 
        if (ptr != NULL)
            { 
              printf("\n Enter the 3 more the elements of the array are \n");
        
               // Get the elements of the array 
               for (i = 0; i < 3; i++) 
                { 
                    printf("The elements of the array are: ");
                    scanf ("%d", ptr + i);            
                } 
      
                // Print the elements of the array 
                printf("\nThe elements of the array are: "); 
                for (i = 0; i < 3; i++) 
                { 
                    printf("%d, ", *(ptr  + i)); 
                } 
            }
            
           // Print the elements of the array 
        printf("\nThe elements of the array are: "); 
        for (i = 0; i < 5; i++) 
        { 
          printf("%d, ", *(ptr  + i)); 
         }     
                 
            
        return 0; 
    }
    Memory successfully allocated using malloc.
    The elements of the array are: 1
    The elements of the array are: 2
    The elements of the array are: 1, 2,
    Enter the 3 more the elements of the array are
    The elements of the array are: 3
    The elements of the array are: 4
    The elements of the array are: 5


    The elements of the array are: 3, 4, 5,
    The elements of the array are: 3, 4, 5, 0, 0,

    Why I don't get output 1, 2, 3, 4, 5?

    Edit : int* ptr = (int*)malloc(5 * sizeof(int));
    Last edited by Dadu@; 02-24-2022 at 11:54 PM.

  2. #2
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    98
    Why I don't get output 1, 2, 3, 4, 5?
    Because the array has only 3 int elements..
    Code:
    ptr = (int*)realloc(ptr, 3 * sizeof(int));
    From my manpages for realloc
    The realloc() function changes the size of the memory block pointed to by ptr to size bytes.
    Try 5 * sizeof(int) and make sure you don't overwrite the first two ints.
    Last edited by G4143; 02-24-2022 at 11:50 PM.

  3. #3
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    Here are some modification in code to print entire array

    Code:
     #include <stdio.h> #include <stdlib.h> 
      
    int main() 
    {     
        int i;
      
        // Dynamically allocate memory using malloc() 
          int* ptr = (int*)malloc(2 * sizeof(int)); 
      
        // Check if the memory has been successfully 
        // allocated by malloc or not 
        if (ptr != NULL) 
        { 
            // Memory has been successfully allocated 
            printf("Memory successfully allocated using malloc.\n"); 
      
        // Get the elements of the array 
           for (i = 0; i < 2; i++) 
           { 
               printf("The elements of the array are: ");
               scanf ("%d", ptr + i);            
            } 
      
            // Print the elements of the array 
            printf("The elements of the array are: "); 
            for (i = 0; i < 2; i++) 
            { 
                printf("%d, ", *(ptr  + i)); 
            } 
        } 
     
     
            
        // Dynamically allocate memory using malloc() 
          ptr = (int*)realloc(ptr, 5 * sizeof(int)); 
      
        // Check if the memory has been successfully 
        // allocated by malloc or not 
        if (ptr != NULL)
            { 
              printf("\n Enter the 3 more the elements of the array are \n");
        
               // Get the elements of the array 
               for (i = 0; i < 3; i++) 
                { 
                    printf("The elements of the array are: ");
                    scanf ("%d", ptr + i);            
                } 
      
                // Print the elements of the array 
                printf("\nThe elements of the array are: "); 
                for (i = 0; i < 3; i++) 
                { 
                    printf("%d, ", *(ptr  + i)); 
                } 
            }
            
           // Print the elements of the array 
        printf("\nThe elements of the array are: "); 
        for (i = 0; i < 5; i++) 
        { 
          printf("%d, ", *(ptr  + i)); 
         }     
                 
            
        return 0; 
    }
    Memory successfully allocated using malloc.
    The elements of the array are: 1
    The elements of the array are: 2
    The elements of the array are: 1, 2,
    Enter the 3 more the elements of the array are
    The elements of the array are: 3
    The elements of the array are: 4
    The elements of the array are: 5


    The elements of the array are: 3, 4, 5,
    The elements of the array are: 3, 4, 5, 0, 0,

  4. #4
    Registered User
    Join Date
    Feb 2022
    Location
    Canada, PEI
    Posts
    98
    You are overwriting the first two elements of your array.
    Code:
    printf("\n Enter the 3 more the elements of the array are \n");     
               // Get the elements of the array 
    
    
    for (i = 0; i < 3; i++)             { 
                    printf("The elements of the array are: ");
                    scanf ("%d", ptr + i);            
                }
    should be
    Code:
    printf("\n Enter the 3 more the elements of the array are \n");     
               // Get the elements of the array 
    
    
    for (i = 2; i < 5; i++)             { 
                    printf("The elements of the array are: ");
                    scanf ("%d", ptr + i);            
                }

  5. #5
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    Quote Originally Posted by G4143 View Post
    You are overwriting the first two elements of your array.
    Thank you got it

  6. #6
    Registered User
    Join Date
    Feb 2019
    Posts
    1,047
    Another tip. Avoid using a pointer in realloc and returning the same pointer because if realloc fails you'll get a memory leakage:
    Code:
      ptr = realloc( ptr, 5 * sizeof(int) );
    Instead, use an auxiliar pointer:
    Code:
      int *q;
    
      q = realloc( ptr, 5 * sizeof(int) );
      if ( q == NULL )
      {
        free( ptr );
        /* ... do something with this fail... */
      }
    
      /* Successful? Now you can update ptr! */
      ptr = q;
    You can create a simple wrapper:
    Code:
    // reallocate memory returning 1 with successful, 0 if fails.
    // update the pointer if successful only.
    int reallocmem( void **p, size_t size )
    { return realloc( p, size ) != NULL; }
    Usage:
    Code:
      if ( reallocmem( (void **)&ptr, 5 * sizeof(int) ) )
      {
        // ... do something with reallocated buffer using ptr...
      }
    Last edited by flp1969; 02-25-2022 at 04:55 AM.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,433
    > // reallocate memory returning 1 with successful, 0 if fails.
    That isn't even close to working properly.
    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.

  8. #8
    Registered User
    Join Date
    Feb 2019
    Posts
    1,047
    Sorry:
    Code:
    int reallocmem( void **p, size_t size )
    {
      char *q;
    
      q = realloc( *p, size );
      if ( q )
        *p = q;
    
      return q != NULL;
    }

  9. #9
    Registered User
    Join Date
    Dec 2017
    Posts
    1,466
    Maybe this is going a little too far:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    #define ReallocElems(p, nelems, msg) \
        realloc_memory((void**)&(p), (nelems) * sizeof(*(p)), msg)
     
    void *realloc_memory(void **p, size_t size, const char *msg) {
        void *q = realloc(*p, size);
        if (!q) {
            if (!msg) return NULL;
            perror(msg);
            free(*p);
            exit(EXIT_FAILURE);
        }
        return *p = q;
    }
     
    void print(const int *a, size_t size) {
        printf("[");
        for (size_t i = 0; i < size; ++i)
            printf("%s%d", (i == 0 ? "" : ", "), a[i]);
        printf("]\n");
    }
     
    int main() {
        int *a = NULL;
        int size = 0;
     
        ReallocElems(a, size = 3, "memory error");
        for (int i = 0; i < size; ++i)
            a[i] = i;
     
        print(a, size); // [0,1,2]
     
        {
            int newsize = 8; 
            if (ReallocElems(a, newsize, NULL)) {
                for (int i = size; i < newsize; ++i)
                    a[i] = i * 10;
                size = newsize;
            }
            else
                printf("Cannot expand array. Printing old values.\n");
        }
     
        print(a, size); // [0,1,2,40,50,60,70]
     
        free(a);
     
        return 0;
    }
    The whole problem with the world is that fools and fanatics are always so certain of themselves, but wiser people so full of doubts. - Bertrand Russell

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,433
    Y'all better hope all pointer types have the same representation.
    Question 4.9
    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.

  11. #11
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    This program allocates memory for four integers variabls. I want to see memory locations that has been allocated

    Code:
     #include<stdio.h>
    
    #include<stdlib.h>
    
    
    int main ()
    {
      int i;
      
      int *ptr = malloc( 4 * sizeof(*ptr)); // allocate memory for 4 integers
      
      if( ptr != NULL )
      {
          for ( i = 0; i < 4; i++ )
          {
              printf("%p ", ptr);
              ptr++;
          }
            
      }
      
      return 0;
    }
    00680D48 00680D4C 00680D50 00680D54

    I have allocated memory for only four variable but this program show six memory locatios

    Code:
     #include<stdio.h>
    #include<stdlib.h>
    
    
    int main ()
    {
      int i;
      
      int *ptr = malloc( 4 * sizeof(*ptr)); // allocate memory for 4 integers
      
      if( ptr != NULL )
      {
          for ( i = 0; i < 6; i++ )
          {
              printf("%p ", ptr);
              ptr++;
          }
            
      }
      
      return 0;
    }
    00E50D48 00E50D4C 00E50D50 00E50D54 00E50D58 00E50D5C

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,433
    > I have allocated memory for only four variable but this program show six memory locatios
    That's because you counted to 6 and not 4

    If you counted to 1000, it would print 1000 consecutive addresses.

    It has nothing to do with the amount of memory you allocated.
    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.

  13. #13
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    Quote Originally Posted by Salem View Post
    > I have allocated memory for only four variable but this program show six memory locatios
    That's because you counted to 6 and not 4

    If you counted to 1000, it would print 1000 consecutive addresses.

    It has nothing to do with the amount of memory you allocated.
    I was not sure how much memory allocated

    I believe my program allocates memory for four integer variabls then adds memory for five integer variabls so there is a total memory allocation for nine variabls

    Code:
     #include<stdio.h>
    #include<stdlib.h>
    
    int main ()
    {
      int i;
      
      int *ptr = malloc( 4 * sizeof(*ptr)); // allocate memory for 4 integers
      
      if( ptr != NULL )
      {
         ptr = realloc( ptr, 9 * sizeof(*ptr)); // allocate memory for 5 integers    
      }
      
      return 0;
    }

  14. #14
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,433
    > I believe my program allocates memory for four integer variabls then adds memory for five integer variabls so there is a total memory allocation for nine variabls
    Yes, that's right.
    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.

  15. #15
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    Quote Originally Posted by Salem View Post
    > I believe my program allocates memory for four integer variabls then adds memory for five integer variabls so there is a total memory allocation for nine variabls
    Yes, that's right.
    Thank you very much

    Is a total memory allocation for two variabls ?

    Code:
     #include<stdio.h>
    
    #include<stdlib.h>
     
    int main ()
    {
      int i;
       
      int *ptr = malloc( 4 * sizeof(*ptr)); // allocate memory for 4 integers
       
      if( ptr != NULL )
      {
         ptr = realloc( ptr, 2 * sizeof(*ptr)); 
      }
       
      return 0;
    }
    I think yes, program first allocats memory for four variables and then release memory for two variables

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. why can't a static array copy values from a dynamic array
    By c++noob145 in forum C++ Programming
    Replies: 2
    Last Post: 03-13-2013, 10:25 AM
  2. Replies: 10
    Last Post: 12-03-2011, 02:26 PM
  3. Copy array into a Dynamic array
    By pantherman34 in forum C Programming
    Replies: 15
    Last Post: 05-01-2010, 10:58 PM
  4. dynamic array
    By Antimodes in forum C++ Programming
    Replies: 8
    Last Post: 04-23-2009, 06:06 AM
  5. Dynamic structure with array and array count
    By Nazgulled in forum C Programming
    Replies: 14
    Last Post: 06-08-2007, 10:10 PM

Tags for this Thread