I'm trying to write an effective function that receives an array the size of n and a and b.
The function should search all the numbers in the array such that b-a < array[i] and collect them to a new sorted array called incoming.
For instance, for the input 11,12,8,15,3,12,3,12 , b=15, a=8 the output would be a 6 size array that will contain the values 8,11,12,12,12,15 (anything that is higher than (b)15-(a)8 ).
This is my own code attempt:
#include<stdio.h>
#include<stdlib.h>
int* f5(int arr[], int n, int a, int b, int* p)
{
int i,min,minIndex;
int* incoming = (int*)malloc(*p*sizeof(int));
for ( i = 0; i < n; i++)
{
if (arr[i]>(b - a))
{
incoming[i] = arr[i];
(*p)++;
}
}
return *incoming;
}
void main()
{
int arr[] = { 12,3,12,3,15,8,12,11 };
int p, i;
int incoming[] = f5(arr, sizeof(arr) / sizeof(arr[0]), 8,15, &p);
printf("The size is: %d and the new marahc is: ", p);
for (i = 0; i < p; i++) {
printf("%d", incoming[i]);
}
free(incoming);
}
So I corrected your f5 function because you were not allocating your new array properly, since you were doing the malloc with (*p) before it was set to the number of elements you needed to store. After that, I ordered the incoming array in ascending order as shown in the example output with qsort. I also added the part where you take input values from the user, since in the code you've posted you were probably just trying that specific test case.
#include<stdio.h>
#include<stdlib.h>
// compare function for qsort
int mycompare (const void* a, const void* b) {
int val1 = *(const int*)a;
int val2 = *(const int*)b;
return (val1 - val2);
}
int* f5(int arr[], int n, int a, int b, int* p) {
int target = b - a;
int i;
for (i=0;i<n;i++) { // storing number of values > (a-b)
if (arr[i]>target) (*p)+=1;
}
int* incoming;
if ((incoming= malloc((*p)*sizeof(int)))==NULL); // should always check malloc errors
{
perror("malloc");
exit(EXIT_FAILURE);
}
int j = 0;
i = 0;
while (i<n && j<(*p)) { // storing values in new array
if (arr[i]>target) {
incoming[j] = arr[i];
j++;
}
i++;
}
return incoming;
}
void main() {
int n, a, b, i;
printf("Insert 'a' value: ");
scanf("%d", &a);
printf("Insert 'b' value: ");
scanf("%d", &b);
printf("Insert array size: ");
scanf("%d", &n);
int arr[n];
printf("Insert array values: \n");
for (i=0;i<n;i++) {
scanf("%d", &arr[i]);
}
int size = 0;
int *incoming = f5(arr, n, a, b, &size);
qsort(incoming, size, sizeof(int), mycompare); // sorting array
printf("The size is: %d and the new marahc is: ", size);
for (i=0; i<size;i++) {
printf("%d ", incoming[i]);
}
free(incoming);
}
In f5 you need to determine the required length to allocate. You could either do an initial pass of the arr[] contents to determine the required length, or just set the length to the upper bound n and resize it once the actual length is known.
First approach using an initial pass:
int* f5(int arr[], int n, int a, int b, int* p)
{
int i;
int j;
int* incoming;
j = 0;
for ( i = 0; i < n; i++)
{
if (arr[i]>(b - a))
{
j++;
}
}
incoming = malloc(j*sizeof(int));
if (incoming == NULL)
{
return NULL;
}
j = 0;
for ( i = 0; i < n; i++)
{
if (arr[i]>(b - a))
{
incoming[j++] = arr[i];
}
}
*p = j;
return incoming;
}
Second approach using upper bound for allocated size:
int* f5(int arr[], int n, int a, int b, int* p)
{
int i;
int j;
int* incoming = malloc(n*sizeof(int));
if (incoming == NULL)
{
return NULL;
}
j = 0;
for ( i = 0; i < n; i++)
{
if (arr[i]>(b - a))
{
incoming[j++] = arr[i];
}
}
int* resized_incoming = realloc(incoming, j*sizeof(int));
if (resized_incoming != NULL)
{
incoming = resized_incoming;
}
*p = j;
return incoming;
}
The above have been written to return NULL if malloc returns NULL.
A third approach would be to start with a small amount for incoming and reallocate to a larger amount when necessary.
In main, the variable incoming needs to be changed from an array type to a pointer:
int* incoming = f5(arr, sizeof(arr) / sizeof(arr[0]), 8,15, &p);
Since f5 can now return NULL, the return value should be checked and appropriate action taken:
if (incoming == NULL)
{
fprintf(stderr, "Failed to allocate memory!\n");
exit(EXIT_FAILURE);
}
You also need to add code to sort the filtered numbers.
Related
The program should eliminate any repeating digits and sort the remaining ones in ascending order. I know how to print unique digits but I donĀ“t know how to create a new vector from them that i can later sort.
#include <stdio.h>
void unique(double arr[], int n) {
int i, j, k;
int ctr = 0;
for (i = 0; i < n; i++) {
printf("element - %d : ",i);
scanf("%lf", &arr[i]);
}
for (i = 0; i < n; i++) {
ctr = 0;
for (j = 0, k = n; j < k + 1; j++) {
if (i != j) {
if (arr[i] == arr[j]) {
ctr++;
}
}
}
if (ctr == 0) {
printf("%f ",arr[i]);
}
}
}
int main() {
double arr[100];
int n;
printf("Input the number of elements to be stored in the array: ");
scanf("%d", &n);
unique(arr, n);
}
You can always break a larger problem down into smaller parts.
First create a function that checks if a value already exists in an array.
Then create a function that fills your array with values. Check if the value is in the array before adding it. If it is, you skip it.
Then create a function that sorts an array. Alternatively, qsort is a library function commonly used to sort arrays.
This is far from efficient, but should be fairly easy to understand:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMS 256
int find(double *arr, size_t length, double val)
{
for (size_t i = 0; i < length; i++)
if (val == arr[i])
return 1;
return 0;
}
size_t fill_with_uniques(double *arr, size_t limit)
{
size_t n = 0;
size_t len = 0;
while (n < limit) {
double value;
printf("Enter value #%zu: ", n + 1);
if (1 != scanf("%lf", &value))
exit(EXIT_FAILURE);
/* if value is not already in the array, add it */
if (!find(arr, len, value))
arr[len++] = value;
n++;
}
return len;
}
int compare(const void *va, const void *vb)
{
double a = *(const double *) va;
double b = *(const double *) vb;
return (a > b) - (a < b);
}
int main(void)
{
double array[MAX_NUMS];
size_t count;
printf("Input the number of elements to be stored in the array: ");
if (1 != scanf("%zu", &count))
exit(EXIT_FAILURE);
if (count > MAX_NUMS)
count = MAX_NUMS;
size_t length = fill_with_uniques(array, count);
/* sort the array */
qsort(array, length, sizeof *array, compare);
/* print the array */
printf("[ ");
for (size_t i = 0; i < length; i++)
printf("%.1f ", array[i]);
printf("]\n");
}
Above we read values from stdin. Alternatively, fill_with_uniques could take two arrays, a source and a destination, and copy values from the former into the latter, only when they would be unique.
Remember to never ignore the return value of scanf, which is the number of successful conversions that occurred (in other words, variables assigned values). Otherwise, if the user enters something unexpected, your program may operate on indeterminate values.
I got a question where I need to write a function that reads an integer X and an array A of type int (size N) from the keyboard and eliminates all occurrences of X in A.
for example the input is:
5
1 2 3 4 3
3
and it would return:
A : 1 2 3 4 3
New A : 1 2 4
my code so far is
#include <stdio.h>
#include<stdlib.h>
#define DIM 50
int main() {
int *A;
int N, X;
int *P1, *P2;
do{
scanf("%d", &N);
}while(N<0 || N>DIM);
A= (int*)malloc(N*sizeof(int));
for(P1=A; P1<A+N ; P1++)
scanf("%d ", P1);
printf("\n");
scanf("%d",&X);
printf("A : ");
for(P1=A; P1<A+N ; P1++)
printf("%d ", *P1);
printf("\n");
but I don't know how to continue if you could please help
What you need is to write a function that will erase elements equal to the specified value and reallocate the result array.
Here is a demonstration program where such a function is shown in action.
#include <stdio.h>
#include <stdlib.h>
size_t erase_remove( int **a, size_t n, int value )
{
size_t m = 0;
for (int *p = *a, *q = *a; p != *a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
if (m != n)
{
int *tmp = realloc( *a, m * sizeof( int ) );
if (tmp != NULL)
{
*a = tmp;
}
else
{
m = -1;
}
}
return m;
}
int main( void )
{
size_t n = 5;
int *a = malloc( n * sizeof( int ) );
size_t i = 0;
a[i++] = 1, a[i++] = 2, a[i++] = 3, a[i++] = 4, a[i++] = 3;
int value = 3;
size_t m = erase_remove( &a, n, value );
if (m != -1) n = m;
for (const int *p = a; p != a + n; ++p)
{
printf( "%d ", *p );
}
putchar( '\n' );
free( a );
}
The program output is
1 2 4
If the memory reallocation for the array within the function was not successful the function returns the value (size_t)-1.
The function preserves the order of elements after removing elements equal to the target value.
If to make the function more general that can deal not only with arrays dynamically allocated then it can look very simply.
size_t erase_remove( int *a, size_t n, int value )
{
size_t m = 0;
for (int *p = a, *q = a; p != a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
return m;
}
In this case the caller of the function should reallocate the result dynamically allocated array (if it is required) based on the returned value m from the function.
#define N_MAX 50
#define N_MIN 0
int main(void) {
int n;
do{
scanf("%d", &n);
}while(N<N_MIN || N>N_MAX);
int *array = (int*) malloc(sizeof(int) * n);
int i; // number of elements in array
for (i = 0; i < n; i++) {
scanf("%d", array + i);
}
int x;
scanf("%d", &x);
//remove x from arr
for (int j = 0; j <= i; j++) {
if (*(array + j) == x) {
*(array + j) = *(array + i); // replace removed value by last value in array
i--; // decremment number of elements in array
}
}
// print
for (int j = 0; j <= i; j++) {
print("%d", *(array + j));
}
free(array)
}
Try this out!
#include <stdio.h>
#include <stdlib.h>
// Required Prototypes
int *get_nums(char *, size_t *);
int *remove_num(int *, size_t *, int);
void display(char *, int *, size_t);
int main(int argc, char *argv[])
{
size_t size = 0;
int *arr = get_nums("Enter numbers (seperated by space): ", &size);
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr, size);
arr = remove_num(arr, &size, num);
display("New Array: ", arr, size);
free(arr);
return 0;
}
int *get_nums(char *label, size_t *size)
{
size_t length = 0;
int *arr = NULL;
printf("%s", label);
int c, num;
do {
scanf("%d", &num);
arr = realloc(arr, (length + 1) * sizeof(int));
arr[length++] = num;
} while ( (c = getchar()) != '\n' && c != EOF);
*size = length;
return arr;
}
int *remove_num(int *arr, size_t *size, int num)
{
// Copy elements to the new array
// Return the new array
size_t new_size = 0;
int *new_arr = NULL;
for (size_t i = 0; i < *size; ++i) {
if (arr[i] != num) {
new_arr = realloc(new_arr, (new_size + 1) * sizeof(int));
new_arr[new_size++] = arr[i];
}
}
*size = new_size;
free(arr);
return new_arr;
}
void display(char *label, int *arr, size_t size)
{
printf("%s", label);
for (size_t i = 0; i < size; ++i)
printf("%d ", arr[i]);
printf("\n");
}
The main idea is you create an array of integers. Then you copy those elements to a new array which you do not want to remove. And finally you display the new array. That's all. Yes, it's that simple. ;-)
Enter numbers (seperated by space): 1 2 3 4 3
Enter number to be removed: 3
Old Array: 1 2 3 4 3
New Array: 1 2 4
As #Ahmed Masud said in comments about too many reallocations, here's my modified answer. Please do note that the code below is little bit complex but far more efficient than my previous one.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *a;
size_t length;
size_t capacity;
} Array;
// Required Prototypes
Array *init_Array(void);
void destroy(Array *);
Array *get_nums(char *);
void remove_num(Array *, int);
void display(char *, Array *);
int main(int argc, char *argv[])
{
Array *arr = get_nums("Enter Numbers (seperated by space): ");
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr);
remove_num(arr, num);
display("New Array: ", arr);
destroy(arr);
return 0;
}
Array *init_Array(void)
{
Array *arr = malloc( sizeof(Array) );
arr->capacity = 1;
arr->length = 0;
arr->a = malloc( sizeof(int) );
return arr;
}
Array *get_nums(char *label)
{
printf("%s", label);
Array *arr = init_Array();
int c, num;
do {
scanf("%d", &num);
// check and reallocate
if (arr->length == arr->capacity) {
arr->a = realloc(
arr->a,
(2 * arr->capacity) * sizeof(int)
);
arr->capacity *= 2;
}
arr->a[arr->length++] = num;
} while ((c = getchar()) != '\n' && c != EOF);
return arr;
}
void remove_num(Array *arr, int num)
{
int remv_idx = -1;
int *a = arr->a;
size_t count = 0;
for (size_t i = 0; i < arr->length; ++i) {
if (a[i] == num) count++;
if (a[i] == num && remv_idx == -1)
remv_idx = i;
if (remv_idx != -1 && remv_idx < i && a[i] != num)
a[remv_idx++] = a[i];
}
arr->length -= count;
arr->capacity = arr->length;
arr->a = realloc(a, arr->capacity * sizeof(int));
}
void display(char *label, Array *arr)
{
printf("%s", label);
for (size_t i = 0; i < arr->length; ++i)
printf("%d ", arr->a[i]);
printf("\n");
}
void destroy(Array *arr)
{
free(arr->a);
free(arr);
}
Here I did not consider any new array but removed the elements in place. I'm keeping both of my solution because you might not need the 2nd one if your input space is small. One more thing, since the question did not mention about any reallocations failures so I did not check it in my code.
Here is an approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_arr(int *arr, size_t size);
size_t remove_by_value(int *arr, size_t len, int value)
{
int count = 0; // maintain how many times we see value
int k;
for(k = 0; k < len ; k++) {
if ( arr[k] == value ) {
while(arr[count+k] == value) {
count++;
} // skip over conscutive values
if ( count + k >= len )
break;
arr[k] = arr[k+count];
arr[k+count] = value;
print_arr(arr, len);
}
}
return len-count;
}
void print_arr(int *arr, size_t size)
{
for(int k = 0; k < size; k++) {
printf("%02d ", arr[k]);
}
printf("---\n");
}
int main()
{
int test_values[] = { 0, 1, 3, 2, 3, 5, 4, 7, 8 };
size_t len = sizeof(test_values)/sizeof(int);
int *arr = malloc(len*sizeof(int));
memcpy(arr, test_values, len*sizeof(int));
print_arr(arr, len);
len = remove_by_value(arr, len, 3);
print_arr(arr, len);
arr = realloc(arr, len);
print_arr(arr, sizeof(int)*len);
return 0;
}
It bubbles the value to be extracted to the end of the array and lops it off.
The nice thing is that it doesn't use any extra memory to do its work.
The second part that is that it is NOT O(n^2) I have to think a bit about the complexity of it (seems bigger than O(n))
However it's a simple solution that keeps the order of the array, removes unneeded values simply.
i've put in the print_arr function at each step of the loop so that you can see what's happening.
Hopefully the code is clear in its purpose, if you have questions please comment and I will further explanation.
Notes
I expressly did not use sizeof(*arr) because i wanted it to be a bit more clear as to what it is. In production code one would use sizeof(*arr) instead of sizeof(int) .... However I would not be able to create a consistent example (e.g. remove_by_value would have to be similarly made generic) so I didn't to keep the example simple to understand.
Ok I need to write two functions iterative and recursive to count negative elements in an array and then I need to build main. I was only able to write the recursive function but I cannot call it from main, it is an error somewhere. Can someone help me out solve it and help me with the iterative method?
#include <stdio.h>
main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(array, size)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
A working piece of code is this.You really need to take a look at pointers and the way they work.
Here you can see that I have a pointer ->pointing-< at the start of the array , so by passing the starting address of the array , and the length of the array , your functions knows what it is needed to be done.
#include <stdio.h>
int numero(int* array, int size);
int* recursive_count(int* array, int size , int* counter );
int main()
{
int vektor[100];
int* vekt_ptr = &vektor[0];
int i, madhesia;
int counter;
counter=0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
//int ret = numero(vekt_ptr, madhesia);
recursive_count(vekt_ptr, madhesia , &counter );
int ret = counter;
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array, int size)
{
int count = 0;
int j;
for (j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
int* recursive_count(int* array, int size , int* counter )
{
size--;
if(array[size] < 0 )
{
(*counter)++;
}
if(size==0)
{
return NULL;
}
return recursive_count(array++, size , counter );
}
Let's assume that you want to create dynamically an array of X length.
The compiler is going to have some memory for your array , depending on the length.
You initialize your array , lets say [2][45][1][-5][99]
When you call the function you have to pass where this is stored in memory.
int* vekt_ptr = &vektor[0]; -s going to give as something like 0x56c2e0.
This number is the address of your array , which is the address of the starting point of the array.This is equal with the address of first byte.
So when your function starts , it knows where your array starts and how long it is.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
Any function used in a program shall be declared before its usage.
This function declaration of the function definition
int numero(array, size)
{
// ...
}
is invalid because the types of the parameters array and size are undefined.
For the size of an array and for the count of elements it is better to use an unsigned integer type like for example size_t or at least unsigned int.
The program can look the following way
#include <stdio.h>
#define N 100
size_t iterative_numero( const int array[], size_t size );
size_t recursive_numero( const int array[], size_t size );
int main( void )
{
int vektor[N];
size_t madhesia = 0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%zu", &madhesia);
if ( N < madhesia ) madhesia = N;
/* Input array elements */
printf("Elementet: ");
for ( size_t i = 0; i < madhesia; i++ )
{
scanf( "%d", &vektor[i] );
}
size_t ret = iterative_numero(vektor, madhesia );
printf("\nTotal negative elements in array = %zu\n", ret);
ret = recursive_numero(vektor, madhesia );
printf("Total negative elements in array = %zu\n", ret);
return 0;
}
size_t iterative_numero( const int array[], size_t size )
{
size_t count = 0;
for ( size_t i = 0; i < size; i++)
{
if ( array[i] < 0 )
{
count++;
}
}
return count;
}
size_t recursive_numero( const int array[], size_t size )
{
return size == 0 ? 0 : ( array[0] < 0 ) + recursive_numero( array + 1, size - 1 );
}
the program output might look like
Madhesia e vektorit: 10
Elementet: 0 -1 2 -3 4 -5 6 -7 8 -9
Total negative elements in array = 5
Total negative elements in array = 5
First of all what you did is the iterative method, not recursive. Here I have called a recursive function from the main function.
#include <stdio.h>
int main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("\nElementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
printf("\nno of elements:%d",madhesia);
printf("\n");
for (i = 0; i < madhesia; i++)
{
printf("%d", vektor[i]);
}
printf("\n");
i=0;
int ret = numero(vektor,madhesia,0,i);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int array[],int size,int count,int j)
{
if (j<=size-1)
{
if(array[j]<0)
{
count++;
j++;
numero(array,size,count,j);
}
else
{
j++;
numero(array,size,count,j);
}
}
return count;
}
Put function prototype of numero() before main() to be able to call it. Declare function parameters with type:
int numero(int array[], int size);
int main() {
...
#include<stdio.h>
int numero(int *, int); //Function Prototype (1)
int main() //Return Type (2)
{
int vektor[100];
int i, madhesia;
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array,int size) //Parameters Data Type (3)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
Errors:
You have declared the function after "main()" so the program doesn't know that there is a function, so you have to give the function prototype before "main()" so that the program knows there is function ahead.
You missed writing the return type of "main()" which is integer.
In the function declaration you forgot to write the data type of the parameters.
NOTE: The array is always passed by reference so it has to taken in an integer pointer instead of a normal integer.
Some possible implementations:
int iterativeCountNegativeIntegers (int *array, int size)
{
int result = 0;
for (int i = 0; i < size; ++ i)
if (array[i] < 0)
result += 1;
return result;
}
int recursiveCountNegativeIntegers (int *array, int size)
{
if (size == 0)
return 0;
int partial = *array < 0;
return partial + recursiveCountNegativeIntegers(array+1, size-1);
}
The same, condensed:
int iterativeCountNegativeIntegers_1 (int *array, int size)
{
int result = 0;
while (--size >= 0)
result += *array++ < 0;
return result;
}
int recursiveCountNegativeIntegers_1 (int *array, int size)
{
return (size == 0) ? 0
: (*array < 0) + recursiveCountNegativeIntegers_1(array+1, size-1);
}
Hey i am trying to print largest element in an array using function and pointers. Below is my code but its printing garbage value. Please help.
void findmax(int arr[],int,int*);
void findMax(int arr[], int n, int* pToMax)
{
if (n <= 0)
return; // no items, no maximum!
int max = arr[0];
pToMax = &arr[0];
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
pToMax = (arr+i);
}
}
}
int main()
{
int nums[4] = { 5, 3, 15, 6 };
int *ptr;
findMax(nums, 4, ptr);
printf("The maximum is at address %u\n", ptr);
printf("It's at index %d\n",ptr - nums);
printf("Its value is %d\n", *ptr);
}
With int *pToMax in findMax(int arr[], int n, int* pToMax) and
calling as findMax(nums, 4, ptr); you just pass ptr as a value.
The updated value won't be reflected after function exits.
You need to use **pToMax
to save address.
void findMax(int arr[], int n, int** pToMax)
{
if (n <= 0)
return; // no items, no maximum!
int max = arr[0];
*pToMax = &arr[0]; //Store base address
for (int i = 1; i < n; i++)
{
if (arr[i] > max)
{
max = arr[i];
*pToMax = (arr+i); //Store max address
}
}
}
call using
findMax(nums, 4, &ptr);
void load(int *n, int *x, int **arr)
{
arr = (int**)malloc(sizeof(int*)*(*n));
for(int i = *n; i >= 0; i--)
{
scanf("%d", &arr[i]);
}
}
int main()
{
int n = 0, x = 0;
int *arr;
load(&n, &x, &arr);
printf("%d", arr[1]);
return EXIT_SUCCESS;
}
The program compiles properly, but it throws windows error during the printf() in main function. Displaying just "arr" gives random big numbers. What is wrong here?
arr = (int**)malloc(sizeof(int*)*(*n));
doesn't change anything in main, it only overwrites the copy of the pointer (address of arr in main) that load receives.
What the function should do is change arr in main, for that, you have to dereference the argument,
*arr = (int*)malloc(sizeof(int)*(*n)); // cast for C++ compiler left in
to change the value of arr in main. (The object that the argument arr of load points to, that is arr in main, needs to be changed, hence you need to modify *arr in load.)
The scans should then be
scanf("%d", &(*arr)[i]);
or (equivalent)
scanf("%d", *arr + i);
#include <stdio.h>
#include <stdlib.h>
void load(int *n, int *x, int **arr)
{
int i = 0;
*arr = (int*) malloc(*n * sizeof(int));
if(!*arr) {
perror("Can not allocate memory!");
return;
}
for(i = *n; i >= 0; i--)
{
scanf("%d", *arr + i);
}
return;
}
int main()
{
int n = 0, x = 0;
int *arr;
int i;
/* You probably need to initialize n */
n = 5;
load(&n, &x, &arr);
for(i = n; i >= 0; i--)
{
printf("%d - %d\n", i, arr[i]);
}
return EXIT_SUCCESS;
}