Pass Array as parameter to function

4

Make a program in C that reads an x value, dynamically create a vector of x elements and pass that vector to a function that will read the elements of that vector. Then, in the main program, the filled vector must be printed. In addition, before the end of the program, the allocated memory area must be released. It follows what I did and what is asked in the exercise but I could not fit the part of function. Made in DEV C ++ version 5.11.

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

int main ()
{
int i,n;
printf ("Digite o numero de elementos que deseja \n ");
scanf ("%i",&n);
int *ptr;
    ptr =(int*) malloc (n * sizeof(int));
        int i; 
    for (i=0;i<n;i++)  /*queria passar essa parte do codigo para uma funçao ... essa parte do codigo faz a leitura dos valores do vetor
    {
        printf ("Digite os valores do vetor\n");
        scanf("%d",&ptr[i]);
    }   */
        for (i=0;i<n;i++)
        {
        printf ("%d",ptr[i]);
        }   
    free(ptr);
system("pause>null");
return 0;
}
    
asked by anonymous 04.05.2016 / 16:36

1 answer

7

Just pass the array (pointer) and the number of elements to the function:

#include<stdio.h>
#include<stdlib.h>
void func(int *ptr, int x) {
    for (int i = 0; i < x; i++) {
        printf("Digite o valor %d do vetor\n", i + 1);
        scanf("%d", &ptr[i]);
    }
}
int main () {
    int x;
    printf("Digite o numero de elementos que deseja\n");
    scanf("%i", &x);
    int *ptr = malloc(x * sizeof(int));
    func(ptr, x);
    for (int i = 0; i < x; i++) {
        printf ("%d\n", ptr[i]);
    }   
    free(ptr);
    return 0;
}

See running on ideone .

Organized, consistent, non-redundant code easier to read?

    
04.05.2016 / 16:55