Thread: School task Read from file and create pointer based array of integers

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    10

    School task Read from file and create pointer based array of integers

    Hi Guys,

    I have one more school task to finish an I need some help understanding where should I start from.

    The task is as follows:

    "02 - You have been provided with a text file Vals.txt containing some integer numbers. Create a class named A02.c that opens the text file, reads the integer values and dynamically creates a pointerbased array of integers. You should not assume a fixed length but rather dynamically allocate memory. Make sure to appropriately dispose of the variable prior to ending the application."

    I already did the code to open the file:

    Code:
    #include <stdio.h>
    
    int main()
    {
      FILE *fp; 
    
    
      fp = fopen("vals.txt","r");
    
    
      while( fscanf(fp,"%d",&temp) != EOF )
      {
    
    
    
    
      }  
    }
    But i need to do this "dynamically creates a pointerbased array of integers. You should not assume a fixed length but rather dynamically allocate memory."

    Could you please give me a code example on how to do it?
    I already searched google but can't find anything close to what I need.

    Any help is greatly appreciated.

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Is this C or C++? I'm asking because the assignment refers to A02.c as a "class".
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    10
    Quote Originally Posted by GReaper View Post
    Is this C or C++? I'm asking because the assignment refers to A02.c as a "class".
    It's C. I think that is a typo in the assignment.

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Ok then, about your question: You can resize a dynamically allocated array with the realloc function. Read up on it, it's quite useful.
    Devoted my life to programming...

  5. #5
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Don't forget to call fclose at the end.

    realloc is what you want to use - If you are new to malloc/realloc you might want to read up on it.
    C Programming/stdlib.h/malloc - Wikibooks, open books for an open world
    Casting malloc - Cprogramming.com

    In it's simplest form "malloc()" is the allocation of memory at run time - Note that that memory must also be deallocated "free()" at run time.


    "realloc()" is the changing of size for the allocation of memory at run time. i.e. I originally wanted 5 bytes, but now I need 10... It also needs to be deallocated at run time.

    Give it a go and see if you run into any problems
    Fact - Beethoven wrote his first symphony in C

  6. #6
    Registered User
    Join Date
    Apr 2019
    Posts
    10
    Code:
    #include <stdio.h>#include <stdlib.h>
    int main(int argc, char *argv[])
    {
      FILE *fp;
      int temp;
      int *arr;
      int counter = 0;
    
      fp = fopen("vals.txt", "r");
    
      while (fscanf(fp, "%d", &temp) != EOF) {
        if (arr == NULL) {
          arr = (int *) malloc(sizeof(int));
          arr[0] = &temp;
          counter++;
        } else {
          arr = (int *) realloc(arr, (counter + 1) * sizeof(int));
          arr[counter++] = &temp;
        }
      }
    
      fclose(fp);
      free(arr);
    
      return 0;
    }
    I tried but it fails with segmentation error on the line after realloc. Any idea why this would happen?
    Last edited by Salem; 04-13-2019 at 05:24 AM. Reason: Removed crayola crapola - use copy-as-text / paste-as-text

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Maybe
    Code:
        if (arr == NULL) {
          arr = malloc(sizeof(int));
          arr[0] = temp;
          counter++;
        } else {
          arr = realloc(arr, (counter + 1) * sizeof(int));
          arr[counter++] = temp;
        }
    Remove the casts, you don't need them in C.
    If you're getting "cannot convert void*" errors, then stop using the C++ compiler to compile your C code.
    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
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Your attempt to check if arr == NULL doesn't make sense because you have not initialised arr. Reallocating the dynamic array on each iteration is also rather slow. We might reallocate by some large constant, or by some small factor greater than 1, e.g.,
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define INITIAL_CAPACITY 2
    #define REALLOCATION_FACTOR 2
    
    int main(void)
    {
        FILE *fp = fopen("vals.txt", "r");
        if (!fp)
        {
            // Handle file opening error
            // ...
            // exit by returning EXIT_FAILURE or calling exit
            // ...
        }
    
        size_t capacity = INITIAL_CAPACITY;
        int *arr = malloc(sizeof(arr[0]) * capacity);
        if (!arr)
        {
            // Handle memory allocation failure
            // ...
            // free file resource and exit
            // ...
        }
    
        size_t size = 0;
        int temp;
        while (fscanf(fp, "%d", &temp) == 1)
        {
            if (size >= capacity)
            {
                size_t resized_capacity = capacity * REALLOCATION_FACTOR;
                int *resized_arr = realloc(arr, sizeof(arr[0]) * resized_capacity);
                if (!resized_arr)
                {
                    // Handle memory reallocation failure
                    // ...
                    // either free both file and memory resources and exit,
                    // or don't free memory and break instead of exit
                    // ...
                }
                capacity = resized_capacity;
                arr = resized_arr;
            }
    
            arr[size++] = temp;
        }
    
        fclose(fp);
    
        // Do stuff with arr
        // ...
    
        free(arr);
    
        return 0;
    }
    Last edited by laserlight; 04-13-2019 at 05:42 AM.
    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

  9. #9
    Registered User
    Join Date
    Apr 2019
    Posts
    10
    Quote Originally Posted by laserlight View Post
    Your attempt to check if arr == NULL doesn't make sense because you have not initialised arr. Reallocating the dynamic array on each iteration is also rather slow. We might reallocate by some large constant, or by some small factor greater than 1, e.g.,
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define INITIAL_CAPACITY 2
    #define REALLOCATION_FACTOR 2
    
    int main(void)
    {
        FILE *fp = fopen("vals.txt", "r");
        if (!fp)
        {
            // Handle file opening error
            // ...
            // exit by returning EXIT_FAILURE or calling exit
            // ...
        }
    
        size_t capacity = INITIAL_CAPACITY;
        int *arr = malloc(sizeof(arr[0]) * capacity);
        if (!arr)
        {
            // Handle memory allocation failure
            // ...
            // free file resource and exit
            // ...
        }
    
        size_t size = 0;
        int temp;
        while (fscanf(fp, "%d", &temp) == 1)
        {
            if (size >= capacity)
            {
                size_t resized_capacity = capacity * REALLOCATION_FACTOR;
                int *resized_arr = realloc(arr, sizeof(arr[0]) * resized_capacity);
                if (!resized_arr)
                {
                    // Handle memory reallocation failure
                    // ...
                    // either free both file and memory resources and exit,
                    // or don't free memory and break instead of exit
                    // ...
                }
                capacity = resized_capacity;
                arr = resized_arr;
            }
    
            arr[size++] = temp;
        }
    
        fclose(fp);
    
        // Do stuff with arr
        // ...
    
        free(arr);
    
        return 0;
    }

    Thank you very much laserlight.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read integers from a file
    By hughng92 in forum C Programming
    Replies: 7
    Last Post: 02-04-2018, 02:24 AM
  2. trying to read from file of integers into 2D array
    By Hana Nasser in forum C Programming
    Replies: 3
    Last Post: 09-14-2015, 11:56 PM
  3. Set Variables Based on File Read?
    By lawrencese in forum C Programming
    Replies: 1
    Last Post: 12-09-2013, 10:11 PM
  4. Replies: 9
    Last Post: 06-18-2011, 11:15 PM
  5. How to read from a file into an array or pointer
    By Rataplar in forum C++ Programming
    Replies: 2
    Last Post: 12-10-2010, 09:45 AM

Tags for this Thread