0

"Implement function int *create_dyn_array(unsigned int n) that allocates an int array for n integers. n is given as argument to the function when it is called. After allocating the array, the function should read the given number of integers to the array from user, using the scanf function. After the right amount of integers have been read, the function returns pointer to the dynamically allocated array."

I am getting a segmentation fault no matter what I do. Also, for some reason the scanf takes in 6 integers, even if I change the for loop "n" to a constant like 3 ?? Absolutely mysterious. What am I doing wrong? Thanks for any possible help here...

  int *create_dyn_array(unsigned int n)
    {
        
        int *array = malloc(n * sizeof(*array));
    
        int i;
    
        for (i = 0; i < n; i++) {
            scanf("%d\n", &(*array)[i]);
        }
    
        return *array;
    }
    
    void printarray(const int *array, int size) {
        printf("{ ");
        for (int i = 0; i < size; ++i) {
            printf("%d, ", array[i]);
        }
        printf(" }\n");
    }
    
    int main()
    {
       
        int *array = create_dyn_array(5);
        printarray(array, 5);
    
       return 0;
    }
John
  • 35
  • 4
  • 2
    Change `&(*array)[i]` to `&array[i]` and `return *array` to `return array`. The latter should have given you a warning by the compiler. – kaylum Feb 16 '21 at 22:32
  • Oh, and remove the `"\n"` from the `scanf`. See: [Using ā€œ\nā€ in scanf() in C](https://stackoverflow.com/questions/15443483/using-n-in-scanf-in-c). – kaylum Feb 16 '21 at 22:33

1 Answers1

1

There are some errors in the code that make it not work as expected, in fact it doesn't seem to compile at all. Here is the corrected code with comments:

int *create_dyn_array(unsigned int n)
{

    int *array = malloc(n * sizeof *array);

    // since you use an unsigned int better to not compare it with int
    for (size_t i = 0; i < n; i++) 
    {
        scanf("%d", &array[i]); // your code had the address of a pointer to array 
                                // you need the address of the element of
    }                           // of the array where to store the value
 
    return array; // return the pointer itself
}

void printarray(const int *array, int size)
{
    printf("{ ");
    for (int i = 0; i < size; ++i)
    {
        printf("%d, ", array[i]);
    }
    printf(" }\n");
}

int main()
{

    int *array = create_dyn_array(5);
    printarray(array, 5);

    return 0;
}

That should do it.

anastaciu
  • 23,467
  • 7
  • 28
  • 53