My function is unable to compare 2 pointer values. The main function has two variables a and b. Swap function swaps the value of a and b. In my max function I cant find the bigger number between c and a. It is not working properly as a always become the bigger number.
//swap two varibales
int swap(int *a, int *b )
{
int temp = *a;
*a= *b;
*b = temp;
printf("After swap: A = %d and B = %d", *a, *b);
}
This function takes the input of c and adds all three numbers.
int additon(int *a, int *b, int *c, int *total)
{
printf(" \nInput Numbers you want: ");
scanf("%d", c);
*total = *a + *b + *c;
printf("\n\nTotal value of numbers %d, %d, %d are = %d",*a,*b, *c, *total );
}
Function which compares between a and c [problem] :
int max(int *a, int *b, int *c,int *maxNum)
{
if( a > c)
{
printf("\n\n A = %d is bigger than C = %d", *a,*c);
}
else if( a < c)
{
printf("\n\n A = %d is smaller than C = %d",*a,*c);
}
}
Main function:
int main(int *total, int *maxNum)
{
int *a = 10;
int *b = 20;
int *c;
printf("Before swap: A = %d and B = %d\n", a,b);
swap(&a, &b);
additon(&a, &b, &c, &total);
max(&a, &b, &c, &maxNum);
return 0;
}
You need to dereference the pointers. Like this:
if( *a > *c)
{
printf("\n\n A = %d is bigger than C = %d", *a,*c);
}
else if( *a < *c)
{
printf("\n\n A = %d is smaller than C = %d",*a,*c);
}
In the previous version your were comparing the addresses the pointers held.
Related
A function receives two integer pointers, int* a and int* b. Set the value of *a to their sum, and *b to their absolute difference.
There is no return value, and no return statement is needed.
I got the values for *a but I'm unable to get the code for *b.
#include <stdio.h>
void update(int *a,int *b);
int main() {
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
void update(int *a,int *b)
{
*a+=*b;
*b=*a-*b;
}
You may use a temporally variable to store value of *a and then use it:
int tmp = *a;
*a += *b;
*b = abs(tmp - *b);
A little cleanup. Only the function needs pointers. Your main does not.
#include <stdio.h>
#include <stdlib.h> // abs()
void sum_and_diff( int * a, int * b )
{
int sum = *a + *b;
int diff = abs( *a - *b );
*a = sum;
*b = diff;
}
int main(void)
{
int a, b;
printf( "a? " ); scanf( "%d", &a );
printf( "b? " ); scanf( "%d", &b );
sum_and_diff( &a, &b );
printf( "sum = %d\n", a );
printf( "absolute difference = %d\n", b );
return 0;
}
A simple answer (the simplest?), that doesn't require temporary variables or external functions like abs(), is:
void update(int *a, int *b)
{
*a += *b;
*b = *a-*b-*b;
}
It fixes your code by also subtracting the "extra" *b you just added to *a
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.
I'm trying to get my head around pointers and I'm trying to write a program which will swap two numbers using pointers. However, I'm getting the error as stated in the title. Here is my code:
//This program swaps two numbers using pointers
#include <stdio.h>
void swap(*val1, *val2);
int main() {
int num1, num2;
int *pNum1, *pNum2;
printf("Enter number 1:\n");
scanf("%d", &num1);
printf("Enter number 2:\n");
scanf("%d", &num2);
pNum1 = &num1;
pNum2 = &num2;
printf("Numbers not swapped: %d, %d\n", *pNum1, *pNum2);
swap(pNum1, pNum2);
return 0;
}
void swap(*val1, *val2) {
int temp;
temp = val1;
val1 = val2;
val2 = temp;
printf("Numbers swapped: %d, %d\n", *val1, *val2);
return;
}
void swap(*val1, *val2);
should be
void swap(int *val1, int *val2);
You should then pass
swap(&num1,&num2);
If you pass a pointer then you are passing a copy of it.You need to pass the address. No need of having pointers in the calling function you can directly pass the address of the variables.
void swap(int *p,int *q)
{
int t = *p;
*p = *q;
*q = t;
}
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;
}
This code is working but its not exactly what I want. Is anyone have any idea how to make it correct and without q sort?. The idea is to understand how to use pointers.
The three numbers should be random between -3 and 12. The code below is something similar, and the closest I have found. Any help would be much appreciated. Thanks in advance!!.
#include <stdio.h>
#include <stdlib.h>
//functions
int compare(const void *a, const void *b)
{
const int *ia = a;
const int *ib = b;
if (*ia < *ib)
return -1;
else if (*ia > *ib)
return +1;
return 0;
}
//qsort function
void sort3(int *a, int *b, int *c)
{
int temp[3];
temp[0] = *a;
temp[1] = *b;
temp[2] = *c;
qsort(temp, 3, sizeof(int), &compare);
*a = temp[0];
*b = temp[1];
*c = temp[2];
}
//random function
int rand_int(int a, int b)
{
return rand()%(b-a+1)+a;
}
int main(void)
{
//declaration of variables
int a,b,c;
int rand_int(int a, int b);
srand(time(0));
a = rand_int(-3,12);
b = rand_int(-3,12);
c = rand_int(-3,12);
printf("%i %i %i\n", a, b, c);
sort3(&a, &b, &c);
printf("%i %i %i\n", a, b, c);
return 0;
}
You don't need the compare() function if you don't want to use qsort().
You can rewrite sort3() like this:
void compare_and_swap(int *a, int *b) {
int t;
if (*a > *b) {
t = *a;
*a = *b;
*b = t;
}
}
void sort3(int *a, int *b, int *c) {
compare_and_swap(a, b);
compare_and_swap(a, c);
compare_and_swap(b, c);
}
This is actually a "bubble sort".
This is a lot of trouble to go for to sort 3 integers. Use if statements.
If the goal is actually to understand pointers, they seem intimidating but they're not so bad. Basically, they're a number that happens to be an address. You can manipulate like them numbers, but if you dereference them (with *), you can get the value there. This cuts both ways, though, because there's not much stopping you from dereferencing a value - which probably crashes your program (or more scarily, maybe not).
As long as you keep in mind what's an address and what's a value, you should be OK.