Say I have an array of n characters.
I want to pass the amount, and a pointer to the array to a function, to check for the biggest value in the array. However, I'm unsure how to access the values from the pointer.
#include <stdio.h>
int max(int *numbers, int size) {
int temp = size;
for (int i=0;i<temp;i++) {
/*How do i access the array values?*/
}
return 0;
}
int main(void) {
int amount;
int Array[amount];
int *ptr;
printf("Enter size of array:");
scanf("%d",&amount);
ptr = &Array[amount];
for(int i=0;i<amount;i++) {
scanf("%d",&Array[i]);
}
printf("Number 2 in array: %d",Array[1]);
printf("\n calling function \n");
max(ptr,amount);
return 0;
}
Two problems -- you don't set amount before using it to create Array so you get an undefined-size array, and Array[amount] is past the end of the array. What you want is something more like:
int amount;
int *ptr;
printf("Enter size of array:");
scanf("%d",&amount);
int Array[amount];
ptr = Array;
and having ptr as a separate variable is not terribly useful -- you can just call max(Array, amount)
Related
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");
}
}
I am new to Programming and to Stack overflow, so forgive me if I make any mistakes. I have this program where one array of ints is split into two other arrays depending on if they are larger or smaller than a user inputted int. Right now all the smaller and larger arrays do is copy the first integer regardless of the number put in. Any suggestions/critiques?
/*
This program will separate an input array into two arrays. One array will be filled by
elements greater than a specified number and the other array will be filled by elements
less than the specified number.
*/
#include <stdio.h>
void separate(int *a, int n, int value, int *larger, int *size, int *smaller);
int main()
{
//Find size of array
int length;
int *length_pointer = &length;
printf("Enter the length of the array: ");
scanf("%d", length_pointer);
//Enter array elements
int array[length], *p;
printf("Enter %d numbers: ", length);
for(p = array; p < array + length; p++)
scanf("%d", p);
//Find separating value
int value;
printf("Enter the number to split the array: ");
scanf("%d", &value);
//Declare arrays and call function
int n = 0, larger[length], smaller[length];
separate(array, n, value, larger, length_pointer, smaller);
//Display the arrays
printf("%d\n", *smaller);
printf("%d", *larger);
return 0;
}
/*************************************************************************************
separate finds numbers larger than value in array a and stores them in array larger.
Numbers smaller than or equal to value will be stored in the smaller array.
size points to a variable in which the function will store the number of larger
numbers in the array.
*************************************************************************************/
void separate(int *a, int n, int value, int *larger, int *size, int *smaller)
{
// Delete later *smaller = *larger = *a;
for(a = &n; a < n + size; a++)
if(a[n] > value)
{
larger = &a[n];
}
else if(a[n] <= value)
smaller = &a[n];
return;
}
I modified a bit your code to reach your goal. In order to get array size from user input under C99, you need to dynamically assign it e.g. by calloc(elements_number, element_size_in_bytes) when your program runs. Don't forget to free assigned memory to avoid memory leaks. Like below:
int* array = calloc(user_input, sizeof(int));
...
//some code
...
free(array);
Your separate function looks a bit complex. This part is wrong:
for(a = &n; a < n + size; a++)
What you are doing here is making a point to integer n. a does not point anymore to a source array. So making a call like a[n] when a is &n is like (&n)[n]. n is not changing value also, because you increment pointer to n, not the value it points to.
Next if you want to display array elements do it by using loop, like I did below.
I could not find the purpose of n parameter in your separate function. I used it as amount of real elements in larger array, so I don't have to print all elements.
I hope this answer meats your expectations.
#include <stdio.h>
#include <stdlib.h>
void separate(int *a, int *larger_count, int value, int *larger, int size, int *smaller);
int main()
{
//Find size of array
int length;
int *length_pointer = &length;
printf("Enter the length of the array: ");
scanf("%d", length_pointer);
//Enter array elements
int*array = calloc(*length_pointer, sizeof(int));
int*p;
printf("Enter %d numbers: ", length);
for(p = array; p < array + length; p++)
scanf("%d", p);
//Find separating value
int value;
printf("Enter the number to split the array: ");
scanf("%d", &value);
//Declare arrays and call function
int *larger = calloc(*length_pointer, sizeof(int));
int *smaller = calloc(*length_pointer, sizeof(int));
int larger_count = 0;
separate(array, &larger_count, value, larger, length, smaller);
for (int i = 0 ; i < larger_count ; ++i)
{
printf("%d ", larger[i]);
}
printf("\n");
for (int i = 0 ; i < length - larger_count; ++i)
{
printf("%d ", smaller[i]);
}
printf("\n");
free(array);
free(larger);
free(smaller);
return 0;
}
/*************************************************************************************
separate finds numbers larger than value in array a and stores them in array larger.
Numbers smaller than or equal to value will be stored in the smaller array.
size points to a variable in which the function will store the number of larger
numbers in the array.
*************************************************************************************/
void separate(int *a, int *larger_count, int value, int *larger, int size, int *smaller)
{
for(int x = 0, y = 0, z = 0; x < size; x++)
{
if (a[x] > value)
{
larger[y] = a[x];
y++;
*larger_count = y;
} else
{
smaller[z] = a[x];
z++;
}
}
}
I am trying to scanf values to an array from another function using pointer to pointer. Here's the code:
int initialize(int **arr, int count);
int main()
{
int count;
int *numbers;
scanf("Enter the amount of numbers to enter: %d", &count);
initialize(&numbers, count);
free(numbers);
return 0;
}
int initialize(int **arr, int count)
{
int i = 0;
*arr = calloc(count, sizeof(int));
while(i < count)
{
printf("Nr. %d: ", i + 1);
scanf("%d", &arr[i]);
i++;
}
return 0;
}
It allocates the memory correctly, however, there seems to be a problem inside scanf function in initialize so it crashes after reading in first 2 numbers. Could you help solve it?
arr is a pointer to pointer to int, so 1st make it a pointer to int (before using it like an array) by doing *arr.
So this
scanf("%d", &arr[i]);
should be
scanf("%d", &(*arr)[i]);
or its shorter equivalent
scanf("%d", *arr + i);
Unrelated, but in C it should be at least
int main(void)
Unrelated^2: Sizes and indexes in C best are defined using size_t (coming with stdlib.h).
So the relevant part of your code would look like this:
int main(void)
{
size_t count;
int *numbers;
scanf("Enter the amount of numbers to enter: %zu", &count);
...
int initialize(int **arr, size_t count)
{
size_t i = 0;
*arr = calloc(count, sizeof(int));
while (i < count)
...
Last not least the code misses error checking for the relevant functions:
scanf()
calloc()
Error checking (along with logging the errors) is debugging for free!
I'm new to C and cannot figure out how to pass a pointer of an array to a function. The function should sort user input numbers in ascending order. I think I've missed something crucial in the function.
I'm able to input the user values but that's as far as I've been able to get without errors.
#include <stdio.h>
int sort(int *p, int i); //function declaration
int main()
{
int numbers[10]; // ten element array
int i;
printf("Please enter ten integer values:\n");
for(i=0; i<10; i++)
scanf("%d", (&numbers[i]));
int *p= &numbers; //a pointer that points to the first element of number
sort(int *p, int i); //function
}
//function sorts in ascending order
int sort (int *p, int i) //function definition
{
for (i=0; i<10; i++) //loop through entire array
{
printf("%d\n", *p);
}
return 0;
}
You should write
int *p= numbers;//a pointer that points to the first element of number
sort(p, i); //function
An array passed to a function is converted implicitly to pointer to its first element.
Also the function should look like
//function sorts in ascending order
int sort (int *p, int n) //function definition
{
for ( int i = 0; i < n; i++) //loop through entire array
{
printf("%d\n", *p++);
// or
//printf("%d\n", p[i]);
}
return 0;
}
A pointer is a variable which contains the address in memory of
another variable. Ampersand (&) operator denotes an address in
memory.
int *p= &numbers; this line will hold the first address of the array
element. For printing every element of an array you have to increment
the pointer printf("%d\n", *p++); and when you call a function you
don't need to declare it's argument data type. In this line sort(int
*p, int i); this is a wrong way to calling a function.just call them directly, like this way: sort(p,i); in your case.
#include <stdio.h>
int sort(int *p, int i); //function declaration
int main()
{
int numbers[10]; // ten element array
int i;
printf("Please enter ten integer values:\n");
for(i=0; i<10; i++)
scanf("%d", (&numbers[i]));
int *p= &numbers; //a pointer that points to address of the first element of numbers array
sort(p, i); //function
}
//function sorts in ascending order
int sort (int *p, int i) //function definition
{
for (i=0; i<10; i++) //loop through entire array
{
printf("%d\n", *p++);
}
return 0;
}
This sort function is just printing the value.If you want the complete code Go here
I'm trying to pass an array to a function that sums up all the elements in the array, but I get a bad access error at the line sum+=a[i]; how can i fix this? Here is the code:
#import <Foundation/Foundation.h>
int sum(int*, int);
int main() {
#autoreleasepool {
int size = 0;
int a[size];
int x;
NSLog(#"Enter a size for the array ");
scanf("%i", &size);
NSLog(#"Enter %i numbers to populate the array ", size);
for (int i = 0; i < size; i++) {
scanf("%i", &a[i]);
}
x = sum(a, size);
NSLog(#"The sum of the array is %i ", x);
}
return 0;
}
int sum(int *a, int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
return sum;
}
It is because your array is 0 in size. Writing / Reading from a[i] may / may not crash as it's behavior is undefined.
Instead of
int size = 0;
int a[size];
int x;
NSLog(#"Enter a size for the array ");
scanf("%i", &size);
you should do this instead:
int size = 0;
int *a;
int x;
NSLog(#"Enter a size for the array ");
scanf("%i", &size);
a = malloc(sizeof(int) * size);
By dynamically allocate the array a, your program should no longer crash.
And after we use malloc, we have to free it when we don't need it anymore. Put this before return 0;
free(a);
Hope this helps.
You've defined an array of size 0. Since an array is a block of memory, and in this case a block of "no" memory, you cannot store anything into it.
You can use malloc/free as indicated in #Owen's answer. C99 also added the ability to declare arrays on the stack (so-called VLA, Variable Length Arrays). This saves you using malloc/free but leaves you at risk of using up all your stack space. For values which you know for a fact will be constrained, a VLA might make sense:
int size;
NSLog(#"Enter a size for the array ");
scanf("%i", &size);
int arr[size];
....
Note that in C89/C90/ANSI you would not be able to do that, since the size of an array must be a compile-time constant.