Why address of the variable changes after passing the function - c

I need to find the smallest and biggest number in the array using pointers; in addition to that, I also need to output the address of these numbers in the main function.
The part I am struggling with is finding the address of the number. The problem is that there are different addresses for the same number. Why is it so?
This is what I get as output:
Please enter a value 0 - 4
Please enter a value 1 - 7
Please enter a value 2 - 2
0x7ffeefbff4fc,4
0x7ffeefbff500,7
0x7ffeefbff504,2
The min value is: 2
The max value is: 7
and address 0x7ffeefbff4f0
#define size 3
void Input (int arr[]);
void AdressOutput (int arr[]);
void MinAndMax (int arr[],int *min,int *max);
int main(void)
{
int arr[size];
int min=0,max=0;
Input(arr);
AdressOutput(arr);
MinAndMax(arr,&min,&max);
printf ("The min value is: %d\n",min);
printf ("The max value is: %d\n and address %p\n",max,&max);
return 0;
}
void Input (int arr[])
{
int i;
int *p=arr;
for (i=0;i<size;i++)
{
printf ("Please enter a value %d - ",i);
scanf ("%d",(p+i));
}
printf ("\n");
}
void AdressOutput (int arr[])
{
int i=0;
int *p=arr;
for (i=0;i<size;i++)
{
printf ("%p,%d\n",(p+i),*(p+i));
}
}
void MinAndMax (int arr[],int *min,int *max)
{
int i=0;
int *p;
p=arr;
*min=*p;
*max=*p;
for (i=0;i<size;i++)
{
if(*(p+i)>*max) //finding max
*max=*(p+i);
}
for (i=0;i<size;i++)
{
if(*(p+i)<*min)//finding min
*min=*(p+i);
}
}
I don't understand why the address changes and how can I create a function which will find addresses and will allow me to print them out in the main function?

In the function MinAndMax arr is your input parameter (parameter given to a function for input) and max and min are output parameters (parameter given to a function for storing output). the function would get the addresses of where to store output from output parameters. output parameters are always addresses, ie the value in these parameters point to the memory where you ultimately want to store your output.
What do you want to store? do you want to store an int OR do you want an address which points to int
you want to print the address of min and max values, so you want to store addresses which points to int
in main function you have declared int min=0,max=0;, these can't store addresses, thay can store only int. so lets change that to int *min_address, *max_address;
you have declared function MinAndMax as void MinAndMax (int arr[],int *min,int *max);. for parameters min and max this means addresses which point to int.
but as you want to store addresses, so what you want in your function is: addresses of memory cells which store the address which points to int. in other words you want a double pointer. so lets change the function declaration to void MinAndMax (int arr[], int **min_address, int **max_address);
here is the corrected code:
#include<stdio.h>
#define size 3
void Input (int arr[]);
void AdressOutput (int arr[]);
void MinAndMax (int arr[], int **min_address, int **max_address);
int main(void)
{
int arr[size];
int *min_address, *max_address;
Input(arr);
AdressOutput(arr);
MinAndMax(arr, &min_address, &max_address);
printf("The min value is: %d\n and adress %p\n", *min_address, min_address);
printf("The max value is: %d\n and adress %p\n", *max_address, max_address);
return 0;
}
void Input (int arr[])
{
int i;
int *p=arr;
for (i=0;i<size;i++)
{
printf("Please enter a value %d - ",i);
scanf("%d",(p+i));
}
printf ("\n");
}
void AdressOutput (int arr[])
{
int i=0;
int *p=arr;
for (i=0;i<size;i++)
{
printf("%p,%d\n",(p+i),*(p+i));
}
}
void MinAndMax (int arr[], int **min_address, int **max_address)
{
int i=0;
int *p;
p=arr;
*min_address=p;
*max_address=p;
for (i=0;i<size;i++)
{
if(*(p+i)>**max_address) //finding max
*max_address=(p+i);
}
for (i=0;i<size;i++)
{
if(*(p+i)<**min_address) //finding min
*min_address=(p+i);
}
}

Related

c program, passing array to function, terminates early

#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size);
int main (void) {
int size, index;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size], element;
for (index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &element);
x[index] = element;
}
void abs_table (double x[], int size);
return 0;
}
void abs_table (double x[], int size) {
int index;
double y[size];
for (index = 0; index < size; index++) {
y[index] = fabs(x[index]);
printf("%lf\t%lf\n", x, y);
}
}
program to read in array values and display the absolute value of each element using a void function.
program terminates after storing values into array x. void function does not display.
Call abs_table() instead of declaring it in main().
Index x and y in abs_table() print statement. As you don't use y other than to print the current value eliminate it.
(minor) Move main() after function so you don't need the declaration.
(minor) Minimize scope of variables.
(minor, not fixed) If your size argument is before x, then you can document their relationship void abs_table(int size, double x[size]).
(minor. not fixed) prefer unsigned variables (index, size etc).
(not fixed) check if scanf() returns 1 in your code otherwise the values size and x[index] may be undefined.
#include <stdio.h>
#include <math.h>
void abs_table (double x[], int size) {
for (int index = 0; index < size; index++) {
printf("%lf\t%lf\n", x[index], fabs(x[index]));
}
}
int main (void) {
int size;
printf("Enter number of elements: ");
scanf("%d", &size);
double x[size];
for (int index = 0; index < size; index++) {
printf("Enter x[%d]: ", index);
scanf("%lf", &x[index]);
}
abs_table(x, size);
return 0;
}
Here is an example run;
Enter number of elements: 3
Enter x[0]: -1.2
Enter x[1]: 1.3
Enter x[2]: -100
-1.200000 1.200000
1.300000 1.300000
-100.000000 100.000000

Accepting values of array in a function and using it in another function, How is this Works in C?

in a program to accept an array and display it on the console using functions getArray() and displayArray() how this program works as it Accepts values of array in function getArray() and uses it in the function displayArray() without returning any values from the first function?
I tried this program and failed to get result, then found this one in youTube comment section and I tried it and got results! I want to know how this program works ?
Q:Write a program to accept an array and display it on the console using function?
a.Program should contain 3 functions including main() function,
main() - {
Declare an array.
Call function getArray().
Call function displayArray() }.
getArray() -
Get values to the array.
displayArray() -
Display the array values
#include <stdio.h>
#include <stdlib.h>
void getArray(int);
void displayArray(int);
int main(void) {
int limit;
printf("Enter The Size of the Array :");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
return EXIT_SUCCESS;
}
void getArray(int limit){
int i,a[100];
printf("Enter The Values of Array :\n");
for(i=0;i<limit;i++){
scanf("%d",&a[i]);
}
}
void displayArray(int limit){
int i,b[100];
printf("Your Array is :\n");
for(i=0;i<limit;i++){
printf(" %d\t",b[i]);
}
printf("\n");
}
Array a in getArray is a local variable that gets destroyed when it goes out of scope. Array b in displayArray is also a local variable (local to displayArray) and has no relationship with a in getArray. You need to pass the same array to both functions.
One way could be to allocate the needed memory for the array in main and pass that, along with the number of elements in the array, to the two functions.
Example:
#include <stdio.h>
#include <stdlib.h>
// a is now a pointer to the first element in the array:
void getArray(int *a, int limit) {
printf("Enter The Values of Array :\n");
for(int i = 0; i < limit; i++) {
scanf("%d", &a[i]);
}
}
// b is now a pointer to the first element in the array:
void displayArray(int *b, int limit) {
printf("Your Array is :\n");
for(int i = 0; i < limit; i++) {
printf(" %d\t", b[i]);
}
putchar('\n');
}
int main(void) {
int limit;
printf("Enter The Size of the Array :");
if(scanf("%d", &limit) != 1 || limit < 1) return EXIT_FAILURE;
// allocate memory for `limit` number of `int`s:
int *arr = malloc(limit * sizeof *arr);
if(arr == NULL) return EXIT_FAILURE;
getArray(arr, limit); // pass arr + limit
displayArray(arr, limit); // pass arr + limit
free(arr); // and free the memory when done
return EXIT_SUCCESS;
}
#include<stdio.h>
void getArray(int);
void displayArray(int);
int array[100];
void main()
{
int limit;
printf("enter the array size you want\n");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
}
void getArray(int limit)
{
printf("enter the array element you want\n");
for(int i=0;i<limit;i++)
{
scanf("%d",&array[i]);
}
}
void displayArray(int limit)
{
for(int i=0;i<n;i++)
{
printf("%d",array[i]);
printf("\t");
}
}

C array manipulation in function

In this code i want to user to input numbers in the function then print the array in the main method, but when i try to print in the main method it gives me random numbers.
for eg:
1 2 3
gives
1 3 1895586112
void arrayInput(int *arr) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
int main(int argc, char **argv){
int *arr[3];
arrayInput(&arr);
int i;
for(i=0; i<3; i++)
{
printf("%d ", arr[i]);
}
}
I want to change the array values without changing the method or param type
int *arr[3] is an array of pointers to int. But you want an array of int.
Simply change:
int *arr[3];
arrayInput(&arr);
to
int arr[3];
arrayInput(arr);
This should be covered in your C text book.
Bonus:
You can remplace this convoluted code:
void arrayInput(int *arr) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
with this:
void arrayInput(int *arr) {
printf("enter 3 numbers =");
scanf("%d %d %d", &arr[0],&arr[1], &arr[2]);
}
There are multiple issues with your code.
First you have declared int *arr[3]; which would mean pointer arrays. For your task a simple array is needed. The array variable contains the address of the first element, so you don't need &.
A simple corrected code is as follows:
#include <stdio.h>
void arrayInput(int arr[]) {
int x;
int y;
int z;
printf("enter 3 numbers =");
scanf("%d %d %d", &x,&y,&z);
arr[0]=x;
arr[1]=y;
arr[2]=z;
}
int main(int argc, char **argv){
int arr[3];
arrayInput(arr);
int i;
for(i=0; i<3; i++)
{
printf("%d ", arr[i]);
}
}

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

using #define in functions

How do i make it so that i can use #define variables in my functions? I need to create a program that calls upon functions with this code. Basically my functions at the bottom can change but my main function cannot change from this kind of format, so however i write my functions i have to pass the variable a and variable SIZE through the functions. But current it seems that SIZE is not actually recognized as an int variable.
#include <stdio.h>
#define SIZE 9
int i, position, tmp;
void readArray(int a[]);
void printArray(int a[]);
void sortArray(int a[]);
int main(void)
{
int a[SIZE];
readArray(a);
printArray(a);
sortArray(a);
printf("After sorting:\n");
printArray(a);
return 0;
}
//Functions//
void readArray(int a[]){
printf("Please enter %d integers: ", SIZE);
for (i=0; i<SIZE; i++) {
scanf("%d", &a[i]);
}
}
void printArray(int a[]){
for (i=0;i<SIZE;i++) {
printf("a[%d] = %3d\n", i, a[i]);
}
}
void sortArray(int a[]){
for (i=0; i<SIZE; i++) {
// In each iteration, the i-th largest number becomes the i-th array element.
// Find the largest number in the unsorted portion of the array and
// swap it with the number in the i-th place.
for (position=i; position<SIZE; position++) {
if (a[i] < a[position]) {
tmp = a[i];
a[i] = a[position];
a[position] = tmp;
}
}
}
}
Writing
#define SIZE 9
will tell the preprocessor to replace each appearance of SIZE with 9.
meaning, the following line -
void sortArray(int a[], int SIZE)
will be replaced with -
void sortArray(int a[], int 9)
I assume you understand this is illegal.
You should just delete the second function parameter.
You should rename the C variables to something other than SIZE. This is already used by the preprocessor. Also, watch out because you've written Int instead of int.

Resources