Misery Misery - 19 days ago 5
C Question

Pointing to arrays using void function

Sorry for that title. I really didn't know how to define this problem.

I was needed to declare integer array of N numbers and to fill it with random nums in void function. Then that array needs to be printed in main. The thing is that i am not allowed to use printf in void function so only way to print in main is to use pointers I guess. My knowledge is limited as I am beginner at pointers. Thx in advance and sorry for bad english.

Here is my code so far. When I compile it marks segmentation error.

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

void form();

int main()
{

int N, a[100];

printf("Input index: \n");
scanf("%d", &N);

form(N, &a);

printf("Array: \n");

for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}

}


void form(int N, int *ptr[100])
{

srand(time(NULL));

for (int i = 0; i < N; i++) {
*ptr[i] = rand() % 46;

}

usr usr
Answer

There are several issues in your code.

1) Your array decalaration form() is obsolete. Use proper prototype.

2) For declaring a VLA, declare it after reading N instead of using a fixed size array.

3) An array gets converted into a pointer to its first element when passed to a function. See: What is array decaying?


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

void form(int, int*); /* see (1) */

int main(void) /* Standard complaint prototype for main. 
                 If you need to pass arguments you can use argc, and argv */
{
    int N;

    printf("Input size: \n");
    scanf("%d", &N);

    int a[N];   /* see (2) */
    form(N, a); /* see (3) */
    printf("Array: \n");

    for (int i = 0; i < N; i++) {
        printf("a[%d] = %d", i, a[i]);
    }
}


void form(int N, int *ptr) { /* Modified to match the prototype
    srand(time(NULL));

    for (int i = 0; i < N; i++) {
        ptr[i] = rand() % 46;

    }
}