Return an array in c with pointers - c

I am trying to make a program that makes simple things. Actually, I know how to do it but in an easier way without pointers and stuff. However, I wondered how I could do it differently (like I did below). Obviously, there is something I miss about pointers, I did the math, but still I cannot get its philosophy.
Thank you!
long *read_array(int n1, int n2)
{
int i, j;
long a[n1][n2];
for(i=0;i<n1;i++)
for(j=0;j<n2;j++)
printf("Fill the table");
a[i][j]=GetLong();
return a;
}
long *Min_of_Rows(int m, int n, long *a)
{
long B[];
int i, j;
for(i=0;i<m;i++)
B[i]=a[i][0];
for(j=0;j<n;j++)
if (a[i][j]<B[i])
B[i]=a[i][j];
return B;
}
void *Print_B_array (int M, long *b)
{
int i;
for(i=0; i<M; i++)
printf("%ld\n",b[i]);
}
main()
{
long *a, *b;
int n1, n2;
printf("give rows");
n1=GetInteger();
printf("give columns");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_rows(n1, n2, a);
Print_B_Array(n1, b);
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long *read_array(int n1, int n2){
int i, j;
long a[n1][n2];
printf("Fill the table\n");
for(i=0;i<n1;i++){
for(j=0;j<n2;j++){
a[i][j]=GetLong();
}
}
long *ret = malloc(sizeof(a));
memcpy(ret, a, sizeof(a));
return ret;
}
long *Min_of_Rows(int m, int n, long *a){
long *B = malloc(m*sizeof(*B));
int i, j;
long (*A)[n] = (void*)a;
for(i=0;i<m;i++){
B[i]=A[i][0];
for(j=0;j<n;j++){
if(A[i][j]<B[i])
B[i]=A[i][j];
}
}
return B;
}
void *Print_B_Array (int M, long *b){
int i;
for(i=0; i<M; i++)
printf("%ld\n", b[i]);
}
int main(void){
long *a, *b;
int n1, n2;
printf("give rows:");
n1=GetInteger();
printf("give columns:");
n2=GetInteger();
a=read_array(n1, n2);
b=Min_of_Rows(n1, n2, a);
printf("min of rows\n");
Print_B_Array(n1, b);
free(a);
free(b);
return 0;
}

Related

When I use qsort for submitting my code in cses problems set it is not accepting it. Is there any other way to resolve this?

#include <stdio.h>
#define ll long long
#include <stdlib.h>
ll int comp(const void* a, const void *b)
{
return *(long long *)b - *(long long *)a;
}
int main(int argc, const char * argv[])
{
ll int n;
scanf("%lld", &n);
ll int a[n];
for(int i=0; i<n; i++)
{
scanf("%lld",(a+i));
}
qsort(a, n, sizeof(ll int), comp);
ll int cnt=0;
for(int i=0; i<n; i++)
{
if(a[i] != a[i+1])
{
cnt++;
}
}
printf("%lld\n", cnt);
cnt=0;
return 0;
}

Changing **array + a to *array[a]

What my program does is it finds 2 numbers of an array that are closest to the average, one is bigger, one is smaller. It works fine, however I need to change for example **array+a to *array[a].
However, when I load the program, it crashes after I input the numbers. If I try to print *array[0], *array[1], etc. it works fine. When I try to print or just do something with *array[a], *array[b], it crashes. Thank you for your help.
#include <stdio.h>
#include <stdlib.h>
int input (int *t, int *array[]);
void calculation (int *array[], int *t, int *x, int *y);
void output (int *x, int *y);
int main()
{
int *array, t, x, y;
input (&t, &array);
calculation (&array, &t, &x, &y);
output (&x, &y);
return 0;
}
int input (int *t, int *array[])
{ int n, *ptr;
printf ("How big is the array?");
scanf ("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
int k;
printf ("Enter the numbers:");
for (k=0; k<n; k++)
{ scanf ("%d", ptr + k);
}
*t=n;
*array=ptr;
return 0;
}
void calculation (int *array[], int *t, int *x, int *y)
{ float sum=0, avg;
int min, max;
int more, less;
int a, b, c;
for (a=0; a<(*t); a++)
{sum=sum+ **array + a;
}
avg=sum/(*t);
min= *array[0];
max= *array[0];
for (b=0; b<(*t); b++)
{ if (max < (**array + b)) max=(**array + b);
if (min > (**array + b)) min=(**array + b);
}
more=max;
less=min;
for (c=0; c<(*t); c++)
{ if (((**array + c) < avg) && ((**array + c) > less)) less=(**array + c);
if (((**array + c) > avg) && ((**array + c) < more)) more=(**array + c);
}
*x=less;
*y=more;
}
void output (int *x, int *y)
{ printf("Number that is less than the average:%d\n", *x);
printf("Number that is more than the average:%d\n", *y);
}
It would be better to rethink your function prototypes a bit. It makes sense to pass a pointer to array to the input() function since you are allocating memory for it, and you want to be able to access it when you return. But you don't need to pass in the pointer to int t; instead, just return the value of n, and assign it to t in main.
There is no reason to pass a pointer to array to the function calculation(), since you are not changing the array allocation. You can also pass in the value of t from main(), since you only use this value in calculation(), but do not change it.
Similarly, the output() function only needs copies of x and y, since it does not change them.
The rule of thumb here is that you pass a pointer to a value into a function when you want to modify the value inside the function and have access to the modified value in the calling function. But you can also return a value instead of using a pointer to it.
These changes do not alter the functionality of your code, but they substantially improve its readability. You even get a sense of what is being modified in each function just by looking at the function prototypes. Well, the changes do alter the functionality in that your original **array + a was incorrect, and needed to be either *(*array + a) or (*array)[a]. But sorting that problem out should help you to appreciate the virtue of the simpler function prototypes. Here is the modified code:
#include <stdio.h>
#include <stdlib.h>
int input(int *array[]);
void calculation(int array[], int t, int *x, int *y);
void output(int x, int y);
int main(void)
{
int *array, t, x, y;
t = input(&array);
calculation(array, t, &x, &y);
output(x, y);
return 0;
}
int input(int *array[])
{ int n, *ptr;
printf("How big is the array?");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
int k;
printf("Enter the numbers:");
for (k=0; k<n; k++)
{ scanf("%d", ptr + k);
}
*array=ptr;
return n;
}
void calculation(int array[], int t, int *x, int *y)
{ float sum=0, avg;
int min, max;
int more, less;
int a, b, c;
for (a=0; a<t; a++)
{sum=sum+ array[a];
}
avg=sum/t;
min= array[0];
max= array[0];
for (b=0; b<t; b++)
{ if (max < array[b]) max=array[b];
if (min > array[b]) min=array[b];
}
more=max;
less=min;
for (c=0; c<t; c++)
{ if ((array[c] < avg) && (array[c] > less)) less=array[c];
if ((array[c] > avg) && (array[c] < more)) more=array[c];
}
*x=less;
*y=more;
}
void output(int x, int y)
{ printf("Number that is less than the average:%d\n", x);
printf("Number that is more than the average:%d\n", y);
}
Just like BLUEPIXY and Some programmer dude said, it's supposed to be (*array)[a]

[C Programming]Vectors & Pointers

I don't have idea where is the problem but the latest pointer(vector) have some troubles.
First value it's ok (V[0]+T[0]) , S[1] it's always 0 and third value it's random.
#include <stdio.h>
#include <stdlib.h>
int citire_vector(int n, int *V);
void afisare_vector(int n, int *V);
int produs_scalar(int n, int *V, int *T);
int suma_vectori(int n, int *V, int *T);
int main(void)
{
int n, *X, *Y, ps, *S;
printf("n = ");
scanf("%d",&n);
X = (int*) malloc(n*sizeof(int));
Y = (int*) malloc(n*sizeof(int));
citire_vector(n,X);
citire_vector(n,Y);
afisare_vector(n,X);
afisare_vector(n,Y);
ps = produs_scalar(n,X,Y);
printf("Produsul scalar = %d\n",ps);
S = (int*) malloc(n*sizeof(int));
*S= suma_vectori(n,X,Y);
afisare_vector(n,S);
}
int citire_vector(int n, int *V)
{
int i;
for(i=0;i<n;i++)
scanf("%d",V+i);
return *V;
}
void afisare_vector(int n, int *V)
{
int i;
printf("Valorile vectorului sunt:\n");
for(i=0;i<n;i++)
printf("%d ",*(V+i));
printf("\n");
}
int produs_scalar(int n, int *V, int *T)
{
int i, ps = 0;
for(i = 0;i<n;i++)
ps += (*(V+i))*(*(T+i));
return ps;
}
int suma_vectori(int n, int *V, int *T)
{
int i, *U;
for(i=0;i<n;i++)
{
*(U+i )= *(V+i);
}
return *U;
}
Your suma_vectori and its usage are incorrect.
Pointer U inside suma_vectori is uninitialized, causing undefined behavior on assignment
Assignment *S= suma_vectori(n,X,Y) has no effect beyond the initial element of S
To fix this problem, change suma_vectori to return int*, move malloc of the result inside the function, remove malloc for S, and assign S the result of the suma_vectori call:
int *suma_vectori(int n, int *V, int *T); // forward declaration
int *suma_vectori(int n, int *V, int *T) { // Implementation
int *U = malloc(n*sizeof(int)); // do not cast malloc
for(int i=0;i<n;i++) {
U[i] = V[i] + T[i];
}
return U;
}
// call
S= suma_vectori(n,X,Y);
// Don't forget to free malloc-ed memory
free(X);
free(Y);
free(S);
You have to allocate memory to U in suma_vectori function
as it is picking garbage value

Using pointers as a dynamically allocated array

I'm trying to write a program that dynamically allocates memory for an array, which the user then fills with integer values and the program sorts said integer values. However, it seems that my array isn't working as intended. I have managed to get the program working with a static array, but the dynamic allocation is causing me a lot of problems with incorrect values and whatnot. Here's what I have so far for the dynamically allocated version (if it would help you guys, I can also provide the version that uses a static array):
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int *numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int *numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2=GetInteger();
numbers=(int *)malloc(i2*sizeof(int));
for(i=0;i<i2;i++, numbers++)
{
printf("Enter next integer: ");
*numbers=GetInteger();
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
Here is a working solution:
#include <stdio.h>
#include <stdlib.h>
void sortArray (int *numbers, int i2);
int indexMax (int *numbers, int low, int high);
void swap (int *num1, int *num2);
int getArray (int **numbers);
void displayArray (int *numbers, int i2);
main()
{
int *numbers, i2;
i2=getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
scanf("%d", &i2);
(*numbers) = malloc(i2 * sizeof(int));
int *temp = *numbers;
for(i = 0; i < i2; i++)
{
printf("Enter next integer: ");
scanf("%d", &temp[i]);
printf("\n");
}
return(i2);
}
void displayArray (int *numbers, int i2)
{
int i;
printf ("\nThe sorted list is: \n\n");
for (i=0;i<i2;i++, numbers++)printf ("%d\n", *numbers);
}
void sortArray (int *numbers, int i2)
{
int i, minInd;
for(i=0;i<i2;i++)
{
minInd=indexMax(numbers, i, i2-1);
swap(&numbers[i], &numbers[minInd]);
}
}
int indexMax (int *numbers, int low, int high)
{
int i, maxInd;
maxInd=high;
for (i=high;i>=low;i--)
{
if(*(numbers+i)>*(numbers+maxInd)) maxInd=i;
}
return (maxInd);
}
void swap (int *num1, int *num2)
{
int temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
The thing is in your main when you are declaring int *numbers , numbers pointer is pointing to some junk memory location as local variables can have any garbage value, so while you are passing this numbers pointer to getArray() function you are passing its value, Suppose numbers is pointing to some random value = 1234 and suppose address of numbers is = 9999. Now when you call getArray(numbers) you tell taht whatever is there in numbers pass it to getArray's numbers variable that we are letting is 1234.
Then when you allocate memory to numbers that is local variable of getArray() function not main's and it might have address suppose = 0x8888. Then malloc allocates some address space as specified and stores the start address of that allocated address space(suppose i.e. = 0x7777) into location 0x8888 not 0x9999 which is the adress of main's numbers variable.
Thus when the getArray function ends and next time you call sortArray you pass it value present in numbers variable of main which is still junk 1234. and the actual value you should be passing is present at address 0x8888.
Try this:
int main(void)
{
int *numbers, i2;
i2 = getArray(&numbers);
sortArray(numbers, i2);
displayArray (numbers, i2);
return 0;
}
int getArray (int **numbers)
{
int i, i2;
printf("Please enter the amount of elements you wish to sort: ");
i2 = GetInteger();
*numbers = malloc(i2 * sizeof int);
etc...
You simply need one more level of indirection to make int getArray(int**) return a pointer to an allocated array.
As an aside, you can use the C library function qsort() to do the sorting work for you. Here is an example:
int main(void)
{
int a[]={4,7,9,1,34,90,66,12};
qsort(a, sizeof(a)/sizeof(a[0]), sizeof(int), compare);
return 0;
}
int compare(const void *a, const void *b){
const int *x = a, *y = b;
if(*x > *y)
return 1;
else
return(*x < *y) ? -1: 0;
}
Works just as well with dynamically allocated int arrays, or char arrays

pointer being realloc'd was not allocated

Actually this is a pure C prog.when i compile with Xcode. error
message says "pointer being realloc'd was not allocated"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int LocateElem(int *p1,int e,int leng1);
void Display(int max, int array[]);
int GetElem(int * p, int pass);
int Union(int *p1,int *p2, int leng1, int leng2);
int ListInsert(int *p, int e, int lengA);
int* GetData(int* pArray, int Array_size);
void Show(int *p, int leng);
void InitList_Sq(int *L);
int *p_A,*p_B;
int m,n;
int main()
{
clock_t begin, end;
double cost;
begin = clock();
printf("How many elements of A u want:");
scanf("%d",&m);
if (m<0) {
printf("Error!");
return 0;
}
printf("How many elements of B u want:");
scanf("%d",&n);
if (n<0) {
printf("Error!");
return 0;
}
p_A=(int *)malloc(m*sizeof(int));
p_B=(int *)malloc(n*sizeof(int));
if (p_A==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
if (p_B==NULL) {
printf("Error allocating memory!\n"); //print an error message
return 0; //return with failure
}
int *pLast_A, * pLast_B;
printf("Array A is :\n");
pLast_A=GetData(p_A, m);
printf("\nArray B is :\n");
pLast_B=GetData(p_B, n);
int newLeng;
newLeng=Union(p_A,p_B,m,n);
printf("\nThe Union set is :\n");
Show(p_A, newLeng);
free(p_A);
free(p_B);
end = clock();
cost = (double)(end - begin) / CLOCKS_PER_SEC;
printf("\n%lf seconds", cost);
return 1;
}
int* GetData(int* pArray, int Array_size){
int* pFill= pArray;
int count;
srand((unsigned) time(NULL));
for ( count=0; count< Array_size; count++) {
*(pFill+count)=rand()%1000;
printf("%d\t", * (pFill+count));
}
return pFill+count;
}
int Union(int *p1,int *p2, int leng1, int leng2){
for (int count=0; count<leng2; count++) {
int e=GetElem(p2, count);
while(LocateElem(p1, e, leng1)==0){
leng1=ListInsert(p1, e, leng1);
}
}
return leng1;
}
int GetElem(int *p, int pass){
return *(p+pass);
}
int LocateElem(int *p1,int e,int leng1){
for (int count=0; count<leng1; count++)
if (e==*(p1+count))
return 1;
else
return 0;
}
int ListInsert(int *p, int e, int lengA){
lengA+=1;
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
if (temp==NULL) {
printf("Error allocating memory!\n"); //print an error message
free(temp);
return 0; //return with failure
}
else{
p=temp;
*(p+lengA-1)=e;
}
return lengA;
}
void Show(int *p, int leng){
for (int count=0; count<leng; count++) {
printf("%d\t", *(p+leng));
}
}
After compilation xcode gives the breakpoint at the line temp=(int*)realloc(p, lengA*sizeof(int)) with signal SIGABRT.
The problem is that here:
int ListInsert(int *p, int e, int lengA){
int* temp;
temp=(int*)realloc(p, lengA*sizeof(int));
...
else {
p=temp; // <<<<< THIS
the new value of p does not propagate back to the ListInsert's caller. This happens because p is passed by value.
You need to turn int *p into int **p.

Resources