C malloc, realloc. How to remove single element from array. - c

I've got a homework to create 2 functions add which adds element to dynamic array (what i've done) and remove which removes indicated element from that array. I have a problem with that 2nd function. I have no clue how to code it.
PS. I can't use memmove().
#include <stdlib.h>
#include <stdio.h>
void print_array(int *tab, int n);
void add(int x, int y, int *tab, int idx);
void remove_element(int *tab, int idx, int array_length);
int main() {
int *tab = malloc(24*sizeof(*tab));
int idx = 0;
tab[idx++] = 44;
tab[idx++] = 82;
tab[idx++] = 57;
tab[idx++] = 77;
printf("Before insert\n");
print_array(tab, idx);
idx++;
add(7, 0, tab, idx);
printf("After insert\n");
print_array(tab, idx);
free(tab);
idx--;
printf("After delete\n");
remove_element(tab, 3, idx);
print_array(tab, idx);
free(tab);
return(0);
}
void print_array(int *tab, int n) {
int i;
for (i = 0; i < n; i++) {
printf("t[%d] = %d\n", i, tab[i]);
}
}
void add(int x, int y, int *tab, int idx) {
int i;
for (i = idx; i > y; i--) {
tab[i] = tab[i-1];
}
tab[y] = x;
}
void remove_element(int *tab, int idx, int array_length) {
void *tmp = realloc(tab, (array_length - 1) * sizeof(int) );
array_length = array_length - 1;
tab = tmp;
}

About your array you can keep information about its size (eg iSize) and the number of elements in use (eg iUse). iUse<=isize, of course.
When you need to add an element but the array is too small (iUse==iSize), you increase its size, add the element and increment iUse.
When you remove an element, you just decrement iUse and, if you can't use memmov, make a loop to move al higher elements down.

Related

Function to generate random ints in array doesn't work

My function does not work and I do not know why, it ends after entering the range. Could you explain why and how to fix it? I need to do this using these pointers to the array.
void generate(int *pa, int *pa2);
void display(int *pa, int *pa2);
int main()
{
srand(time(0));
int size;
printf("Enter size of array\n");
scanf("%d",&size);
int *A=(int*) malloc(size*sizeof(int));
int *ptr=A;
int *pa=&ptr[0];
int *pa2=&ptr[size-1];
generate(pa,pa2);
display(pa,pa2);
return 0;
}
void generate(int *pa, int *pa2)
{
int upper,lower;
int randi;
printf("enter range");
scanf("%d %d",&lower,&upper);
for (int i = 0; i <*pa2; i++)
{
randi=(rand() % (upper - lower + 1)) + lower;
*(pa+i) = randi;
}
}
for (int i = 0; i <*pa2; i++)
You've mixed up iterating by index with iterating until you hit a pointer. That's comparing the value of the end of the array, which is garbage, to i.
Instead you need to compare the pointers pa+1 to pa2. And it has to be <= because you do want to fill in the last item.
for (int i = 0; (pa+i) <= pa2; i++) {
*(pa+i) = ...
}
But it's easier to get rid of i and increment a pointer directly.
void generate(int *start, int *end) {
...
for(int *current = start; current <= end; current++) {
*current = ...;
}
}
But since you have the size, it's simpler to pass in the size and iterate by index.
void generate(int *array, int size) {
...
for (int i = 0; i <= size; i++) {
array[i] = ...
}
}
And you can simplify calling the function. A and &A[0] point to the same memory.
generate(A, &A[size-1]);

Passing pointer to an array as a parameter to a function

I tried to build a heap and finally print the elements in the form of an array.
Here it is the code (I know this doesn't really make sense but I just wanted to test my knowlwdge of heap and dynamic arrays):
#include <stdio.h>
#include <stdlib.h>
void heapiify(int *arr,int n, int i)
{
int largest=i;
int l=2*i+1; // left node
int r= 2*i+2; // right node
if(l<=n && *arr[l]>=*arr[i])
largest=l;
if (r <=n && *arr[r]<=*arr[i])
largest= r;
if(largest !=i)
{
int temp=*arr[i];
*arr[i]=*arr[largest];
*arr[largest]=temp;
}
heapify(*arr,n,largest);
}
void buildh(int *arr,int n,int r,int c)
{
int i;
for(i=n/2-1;i>=0;i--)
heapify(*arr,n,i);
output(*arr,r,c);
}
void output(int *arr,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d",*arr[i*c+j]);
}
printf("\n");
}
}
int main()
{
int i,j,r,c;
printf("enter the number of rows");
scanf("%d",&r);
printf("enter the number of columns");
scanf("%d",&c);
int n=r*c;
int *arr=malloc(n*sizeof(int));
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&arr[i*c+j]);
}
buildh(*arr,n,r,c);
}
I'm getting 9 errors which are all the same
invalid argument type of unary '*'( have int)
Your arr variable is of type pointer to int:
int *arr=malloc(n*sizeof(int));
So when you call buildh, which takes the same type, you have to pass it as-is:
buildh(arr,n,r,c);
Same for the other cases.
The problem is the dereference of arr, across your funtions in multiple places, and the passing of dereferenced *arr in your functions to int * parameters, you should pass arr, try:
//...
void heapify(int *arr, int n, int i)
{
int largest = i;
int l = 2 * i + 1; // left node
int r = 2 * i + 2; // right node
if (l <= n && arr[l] >= arr[i]) //here
largest = l;
if (r <= n && arr[r] <= arr[i]) //here
largest = r;
if (largest != i)
{
int temp = arr[i]; //here
arr[i] = arr[largest]; //here
arr[largest] = temp; //here
}
heapify(arr, n, largest); //here
}
void buildh(int *arr, int n, int r, int c)
{
int i;
for (i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i); //here
output(arr, r, c); //here
}
void output(int *arr, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d", arr[i * c + j]); //here
}
printf("\n");
}
}
int main()
{
//...
buildh(arr, n, r, c); //here
}

Sort elements in array C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to create a program that will sort elements in 4 steps (read elements - print elements - sort them - print the sorted version).
I need help with the sorting (third) part.
Here is my code:
/*
* A simple program to sort numbers in correct order
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
#define SENTINEL -99
int main()
{
int tableFill(int a[], int max);
void tableInsert(int a[], int num, int val);
void tableSort(int a, int n);
void tablePrint(int a, int n);
int num;
int table[MAXSIZE];
int max;
num=tableFill(table,MAXSIZE);
return EXIT_SUCCESS;
}
int tableFill(int a[], int max)
{
int r; // input from scanf
int next; // score from user
int cnt = 0;
printf("Enter the numbers! \n");
while ((r=scanf("%i", &next))!= EOF && cnt<max)
{
if (r == 0) //invalid input data
{
printf("Nonnumeric data entered. Please enter a number. \n");
while (getchar()!= '\n'); // flush invalid data
}
else
a[cnt++]=next;
}
if(r==1) //another value was read but the array is full
printf("Error - too many values. Array size %i.\n", max);
}
void tableInsert (int a[], int num, int val)
{
int pos;
for(pos = num; pos>0 && val<a [pos-1]; pos--)
a [pos] = a [pos -1];
a[pos] = val;
}
void tableSort(int a, int n)
{
}
void tablePrint(int a, int n)
{
int i;
for(i = n -1; i>=0; i++)
{
printf("%i\n",a[i]);
}
}
SOLUTION
I used David C. Rankin's solution and fixed my code. This is my final version:
/*
* A simple program to sort numbers in the correct order
*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10 //max elements in array
int main () {
int tableFill (int a[], int max);
void tableSort (int a[], int n);
void tablePrint (const a[], int n);
int arr[MAXSIZE]; //creating an array
int n = tableFill (arr, MAXSIZE); //declaring variable to work with array
tablePrint (arr, n); //prints unsorted values
printf ("Here is your sorted array:\n");
tableSort (arr, n); // sorts values in order
tablePrint (arr, n); // prints sorted values
return 0;
}
// read values from stdin into array up to 'max' values
int tableFill(int a[], int max) {
int r; // input from scanf
int next; // score from user
int cnt = 0; // loop variable
printf("Enter the numbers! \n");
while ((r=scanf("%i", &next))!= EOF && cnt<max)
{
if (r == 0) //invalid input data
{
printf("Nonnumeric data entered. Please enter a number. \n");
while (getchar()!= '\n'); // flush invalid data
}
else
a[cnt++]=next;
}
if(r==1) //another value was read but the array is full
printf("Error - too many values. Array size %i.\n", max);
return cnt;
}
// swap values at array indexes 'i' and 'j'.
void tableSwap (int a[], int i, int min_index)
{
int tmp = a[i];
a[i] = a[min_index];
a[min_index] = tmp;
}
//sort array
void tableSort (int a[], int n)
{
void tableSwap (int a[], int i, int min_index);
int i, j; //loop counters
int min, min_index; //adjusting variables for loops
for (i = 0; i <= n - 2; i++) {
min = a[i];
min_index = i;
for (j = i + 1; j <= n - 1; j++) {
if (a[j] < min){
min = a[j];
min_index = j;
}
}
tableSwap (a, i, min_index);
}
}
//print all elements in array.
void tablePrint (const a[], int n)
{
int i; //variable for print
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
printf ("\n");
}
As pointed out in the comments, qsort is the defacto standard sort routine contained in the C standard library. It is incredibly flexible and incredibly fast due to using a combination of sorting methods optimized for the range of data being sorted. Beginning C users generally have difficulty writing the compare functions because it involves the use of pointers. Just take the time needed to write a few compare functions are get comfortable with it -- it will save you a lot of grief in the long run.
That said, before looking at both alternative sorts, C-style generally uses lower-case for variable and function names. Leave camelCase names for C++. See e.g. NASA - C Style Guide, 1994
Sorting with the old-slow bubblesort. For sorting anything with greater than 100 elements, the efficiency of the bubblesort craters. It is hundreds of times slower than qsort for any large number of element. That being said, putting a bubblesort together that incorporates your tableswap requirement is straightforward:
/** sort array using slow old bubblesort */
void tablebubblesort (int *a, int n)
{
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) /* For decreasing order use < */
tableswap (a, n, j, j+1);
}
}
}
Your tableswap function will look similar to:
/** swap values at array indexes 'i' and 'j'. */
void tableswap (int *a, int n, int i, int j)
{
if (i >= n || j >= n) return;
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Simply call the function in your code with tablebubblesort (arr, n);
qsort is even simpler. The full function (you really don't need a separate function) is:
/** qsort the array */
void tablesort (int *a, int n, size_t sz)
{
qsort (a, n, sz, compare);
}
It requires a compare function which is simply:
/** qsort compare function */
int compare (const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
Don't let you eyes roll over in your head simply because you see const void *a, etc.. it is really straight forward. Your a and b pointers represent a pointer to individual integers in the array (e.g if say a[1] = 5, the pointer is just &a[1] the address of the element). So taking the compare function apart, knowing you are just passing the address of an element (e.g. integer pointers) to compare, you would write it long-hand as follows:
int compare (const void *a, const void *b)
{
int *value1 = (int *)a; /* cast each to int pointer */
int *value2 = (int *)b;
if (*value1 > *value2) /* compare dereferenced values */
return 1;
if (*value1 < *value2)
return -1;
return 0;
}
Or, if it makes you happier, you can cast and dereference all at once and then just operate on integer values:
int compare (const void *a, const void *b)
{
int value1 = *(int *)a;
int value2 = *(int *)b;
if (value1 > value2)
return 1;
if (value1 < value2)
return -1;
return 0;
}
Either way it is the same. (arguably, the first is the most proper because it avoid the "appearance" of type punning pointers and derefencing void values, but that is for another day) There is no magic, just do it enough times for integers, strings, structs, etc.. until it sinks in. It's more than worth the time.
Putting the rest of the pieces together, you could meet your requirements with something similar to the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXI 128
int tablefill (int *a, int max);
void tableinsert (int *a, int *n, int max, int num, int val);
void tableswap (int *a, int n, int i, int j);
void tablesort (int *a, int n, size_t sz);
void tablebubblesort (int *a, int n);
void tableprint (int *a, int n);
int compare (const void *a, const void *b);
int main (void) {
int arr[MAXI] = {0};
int n = 0;
printf ("enter array values ([ctrl+d] to end)\n");
n = tablefill (arr, MAXI);
tableprint (arr, n);
printf ("\ninsert '5' as the '2nd' element of array\n");
tableinsert (arr, &n, MAXI, 2, 5);
tableprint (arr, n);
printf ("\nswap indexes '1' and '3'\n");
tableswap (arr, n, 1, 3);
tableprint (arr, n);
printf ("\nsorted array\n");
#ifdef WQSORT
tablesort (arr, n, sizeof *arr); /* gcc -DWQSORT to use tablesort */
#else
tablebubblesort (arr, n);
#endif
tableprint (arr, n);
return 0;
}
/** read values from stdin into array up to 'max' values. */
int tablefill (int *a, int max)
{
int idx = 0, tmp;
while (idx + 1 < max && scanf ("%d", &tmp) == 1)
a[idx++] = tmp;
return idx;
}
/** insert 'val' as the 'num' element in 'a' ('num - 1' index),
* update 'n' to current number of elements.
*/
void tableinsert (int *a, int *n, int max, int num, int val)
{
if (num >= max || *n + 1 == max) return;
if (num >= *n) { a[num] = val; (*n)++; return; }
int i;
for (i = *n; i >= num; i--)
a[i] = a[i-1];
a[i] = val;
(*n)++;
}
/** swap values at array indexes 'i' and 'j'. */
void tableswap (int *a, int n, int i, int j)
{
if (i >= n || j >= n) return;
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
/** qsort the array */
void tablesort (int *a, int n, size_t sz)
{
qsort (a, n, sz, compare);
}
/** sort array using slow old bubblesort */
void tablebubblesort (int *a, int n)
{
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) /* For decreasing order use < */
tableswap (a, n, j, j+1);
}
}
}
/** print all elements in array. */
void tableprint (int *a, int n)
{
if (!a) return;
int i;
for (i = 0; i < n; i++)
printf (" a[%2d] : %d\n", i, a[i]);
}
/** qsort compare function */
int compare (const void *a, const void *b)
{
return (*(int *)a - *(int *)b);
}
The code contains both the bubblesort and qsort version of the sort. You simply pass the define -DWQSORT to compile with the qsort code or compile without it for the bubblesort. e.g.
Compile Both Versions
$ gcc -Wall -Wextra -Ofast -o bin/array_fill array_fill.c
$ gcc -Wall -Wextra -Ofast -DWQSORT -o bin/array_fill_qsort array_fill.c
Example Use/Output
$ echo "1 4 2 3" | ./bin/array_fill
enter array values ([ctrl+d] to end)
a[ 0] : 1
a[ 1] : 4
a[ 2] : 2
a[ 3] : 3
insert '5' as the '2nd' element of array
a[ 0] : 1
a[ 1] : 5
a[ 2] : 4
a[ 3] : 2
a[ 4] : 3
swap indexes '1' and '3'
a[ 0] : 1
a[ 1] : 2
a[ 2] : 4
a[ 3] : 5
a[ 4] : 3
sorted array
a[ 0] : 1
a[ 1] : 2
a[ 2] : 3
a[ 3] : 4
a[ 4] : 5
$ echo "1 4 2 3" | ./bin/array_fill_qsort
<same outoput>
Look over all the code and let me know if you have questions. This is basic meat and potatoes C and you need to make sure you understand each line, and each character in each line. Take it slow.
Regarding
int tableFill(int a[], int max);
void tableInsert(int a[], int num, int val);
void tableSort(int a, int n);
void tablePrint(int a, int n);
You're declaring the prototypes inside main which is not usually done. They are usually declared in global scope so that they stay put till the end.
Regarding
int tableFill(int a[], int max)
You're not returning anything. Since you're dealing with the pointers you could change int to void.
Regarding
void tableInsert (int a[], int num, int val)
Ask yourself from where you are calling this function.
Regarding
void tableSort(int a, int n)
{
}
See this guide which explains sorts.
Regarding :
void tablePrint(int a, int n)
{
int i;
for(i = n -1; i>=0; i++)
{
printf("%i\n",a[i]);
}
}
Since you're printing an array,so one parameter to this function should be an array.

C Program, function sorting through pointers

This program is supposed to take an array, and sort it from lowest to highest value. My program won't sort any values though. I believe the error is in the selectionSort. The values i and j are present in the function, I printed them out inside the function but they are not passed into the swap function. I tried making i and j pointers but it didn't work. I just have no clue on what to do next. Any help would be appreciated.
#include <stdio.h>
#define N 5
void selectionSort(int *a, int n);
int *findLargest(int *a, int n);
void swap(int *p, int *q);
int main(void)
{
int i;
int a[N];
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
selectionSort(a, N);
printf("In sorted order:");
for (i = 0; i < N; i++) {
printf(" %d", a[i]);
}
printf("\n");
return 0;
}
void selectionSort(int *a, int n)
{
int *p = a;
int i;
int j;
if (n == 1) {
return;
}
i = *(p+n-1);
j = *findLargest(a, n);
swap(&i, &j);
selectionSort(a, n - 1);
}
int *findLargest(int *a, int n)
{
int *p;
int *p_max = a;
for(p = a + 1; p < a + n - 1; p++) {
if ( *p > *p_max)
p_max = p;
}
return p_max;
}
void swap(int *p, int *q)
{
int temp = *(p-1);
*(p-1) = *q;
*q = temp;
}
The problem is in your call of swap: you swap the content of two local variables
int i;
int j;
... // Some other code, then
swap(&i, &j);
This has no effect on the original array. You should be passing p+n-1 and findLargest(a, n) directly, or store their results in pointers, not in ints:
swap(p+n-1, findLargest(a, n));
In addition, your swap is broken: rather than swapping the content of two pointers, it assumes that p points one element past the target location. This is a bad assumption to make in a general-purpose function, such as swap, and it also leads to undefined behavior in your program.
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}

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

Resources