0

What I could understand is that the function that generates a random array returns the address of the array, and what I can't get to work is the function that receives that address and gets the array's values from it.

My understanding of pointers is really shallow as I've only started working with them recently, if someone could clarify this (as if I were a 5 year old please) and help me make the program work I'd be grateful.

I know doing it all in main would be simpler but I wanted to do it like this to try getting a better understanding of pointers and whatnot, also these functions will help me in other simple exercises.

#include<stdio.h>
#include<stdlib.h>

int* random_array(){
    int size = rand()%100;
    
    if(size == 0){
        size = 1;
    }
    
    int array[size];
    
    for(int i = 0; i < size; i++){
        array[i] = rand()%100;
    }
    
    return array;
}

read_backwards(int* a){ //this is where it gets confusing

    int size = sizeof(a)/sizeof(int);
    
    if(size > 100){
        size = 100; 
    }
    
    int array[size] = &a;
    
    int i = size;
    
    while(array[i] > 0){
        printf("%d", array[i]);
        i--;
    }
}

main(){

    read_backwards(random_array());

}
rorgrs
  • 1
  • You can't usefully return a pointer to a local variable — and especially not an array. You have to allocate the memory so that it continues to be valid after the function is called. You can do that either by allocating the array in the calling function and passing the array to the random initializer, or by having the random initializer dynamically allocate the memory (via `malloc()` et al) and return a pointer to that memory. – Jonathan Leffler Aug 09 '22 at 01:59
  • In `read_backwards(int* a)` you do `int size = sizeof(a)/sizeof(int);` but you can't use sizeof on a pointer - it will always return the size of the pointer and not what it is pointing to - you need to pass the pointer and the size. And `while(array[i] > 0){ ... i--; }` is dangerous - you end up accessing array with negative indicies. You probably also want to call srand at the start of main. Something like this: https://onlinegdb.com/1f8O96Sya – Jerry Jeremiah Aug 09 '22 at 02:25

0 Answers0