I am writing a C program to insert element into an array with pointers. In my INSERT method I can't seem to add the element into the array. when I select option 4, it shows 0 number in the array.
the test case I use is as follows :
run the program
select option 1
Enter an array size
enter the element to add to the array.
select option 4 to display the array
// Online C compiler to run C program online
#include <stdio.h>
#define MAX 10
void initialize (int *size, int ar[]);
void insert (int max, int *size, int ar[], int num);
void iremove (int *size, int ar[], int num);
void display (int size, int ar[]);
int main ()
{
int option = 0;
int num, ar[MAX], size = 0;
printf ("Please select an option: \n");
printf ("(1) Initialize the array \n");
printf ("(2) Insert an integer \n");
printf ("(3) Remove an integer \n");
printf ("(4) Display the numbers stored in the array \n");
printf ("(5) Quit \n");
do
{
printf ("Enter your choice: \n");
scanf ("%d", &option);
switch (option)
{
case 1:
initialize (&size, ar);
break;
case 2:
printf ("Enter an integer: \n");
scanf ("%d", &num);
insert (MAX, &size, ar, num);
break;
case 3:
break;
case 4:
display(size,ar);
break;
default:
break;
}
}
while (option < 5);
return 0;
}
void display (int size, int ar[])
{
int i;
printf ("The %d numbers in the array: \n", size);
for (i = 0; i < size; i++)
printf ("%d ", ar[i]);
printf ("\n");
}
void initialize (int *size, int ar[])
{
int total, i, num;
printf ("Enter the total number of integers (MAX=%d): \n", MAX);
scanf ("%d", &total);
(*size) = 0;
printf ("Enter the integers: \n");
for (i = 0; i < total; i++)
{
scanf ("%d", &num);
insert (MAX, size, ar, num);
}
}
void insert (int max, int *size, int ar[], int num)
{
if(*size>=MAX)
{
printf("Array full")
}
else
{
ar[*size] = num;
}
}
void iremove (int *size, int ar[], int num)
{
/* Write your code here */
}
You forgot to increment the size :
void insert (int max, int *size, int ar[], int num)
{
if(*size>=MAX)
{
printf("Array full")
}
else
{
ar[*size] = num;
(*size)++;
}
}
I would suggest avoiding side effects in the code when possible. Use return values.
Also, try to use the correct types as well. For sizes use size_t defined in many headers *for example stdio.h or stdlib.h)
Your functions should be called append as you do not insert but append the value to the end of the array.
size_t append(size_t max, size_t size, int *array, int num)
{
if(size < max)
{
array[size++] = num
}
else
{
printf("Array full");
}
return size;
}
and the call
size = insert(MAX, size, ar, num);
Related
*I am taking the size of array from user, the program runs perfectly when i declare int arr[n]; below the scanf in main but, it when i run following code is behaves differently each time, sometimes take more values, some times shows bus error. Even the value of n changes sometimes. *
//Code
#include <stdio.h>
void read_array(int arr[], int *n);
void print_array(int arr[], int *n);
int main() {
int n;
int arr[] = {};
printf("Enter array length ");
scanf("%d", &n);
printf("\nmain elements %d", n);
read_array(arr, &n);
printf("\nElements main %d", n);
print_array(arr, &n);
return 0;
}
void read_array(int arr[], int *n) {
int i;
printf("\n Elements R_A %d", *n);
printf("\nEnter elements");
for (i = 0; i < *n; i++) scanf("%d", &arr[i]);
}
void print_array(int arr[], int *n) {
int i;
printf("\n");
for (i = 0; i < *n; i++) printf("%d ", arr[i]);
printf("\n Elements P_A %d", *n);
}
When an array is declared without an explicit size, it size is taken to be the number of elements it is initialized with. So This:
int arr[]={};
Declares an array of size 0 which is invalid, and attempting to use it triggers undefined behavior.
int arr[] = {}; is a zero-length array (not supported by the standard) and you access it out of bounds.
If your compiler supports VLAs (variable length arrays), you could use one of those instead.
Example:
#include <stdio.h>
void read_array(int arr[], int *n);
void print_array(int arr[], int n); // no need to send in a pointer to n
int main() {
int n;
printf("Enter array length ");
if (scanf("%d", &n) != 1 || n < 1) return 1; // check that scanf succeeded
printf("\nmain elements %d", n);
int arr[n]; // a VLA of n elements
read_array(arr, &n);
printf("\nElements main %d", n);
print_array(arr, n);
return 0;
}
void read_array(int arr[], int *n) {
printf("\n Elements R_A %d", *n);
printf("\nEnter elements");
int i;
for (i = 0; i < *n; i++) {
if (scanf("%d", &arr[i]) != 1) break; // check that scanf succeeded
}
*n = i; // store the number of elements successfully read
}
void print_array(int arr[], int n) {
int i;
printf("\n");
for (i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n Elements P_A %d", n);
}
I can't figure out how to print array elements from my function into the main program so if some can examine this code and help me fix it I would appreciate it. The program is supposed to take the length of the array from user input and then ask for its elements and print them out afterward.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int arrayN(int N) {
printf("Input array lenght: ");
scanf("%d",&N);
if(N>2) {
return N;
} else {
return 0;
}
}
int arrayelements(int array[], int array_length) {
int loop, i, N;
array_length = arrayN(N);
printf("Enter elements of the array: \n");
for(int i = 0; i < array_length; ++i) {
scanf("%d", &array[i]);
}
for(loop = 0; loop < array_length; loop++) {
printf("%d ", array[loop]);
}
}
int main() {
int N, array[], array_length;
int b = arrayelements(array[], array_length);
int a = arrayN(N);
printf("Array length is: %d \n", a);
printf("Elements of array are: %d \n", b);
return 0;
}
I reworked your example code. Hope it is what you want.
Focus lied on fixing the array declaration issues, memory allocation and
user input.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
int userinput_integer(const char *fmt, ...){
int N, rv = 0;
va_list va;
va_start(va, fmt);
vprintf(fmt, va);
while(1){
rv = scanf("%d", &N);
if (1 == rv) break;
printf("Input error! The input >>");
do{
rv = fgetc(stdin);
if (isprint(rv)) putchar(rv);
}while(rv != EOF && rv != '\n');
printf("<< is not a valid integer.\nPlease try again: ");
}
va_end(va);
return N;
}
int userinput_arraylength(void) {
int N;
N = userinput_integer("Input array lenght: ");
if(N>2) {
return N;
} else {
printf("Invalid length\n");
return 0;
}
}
int userinput_arrayelements(int *array, int N) {
printf("Enter elements of the array: \n");
for(int i = 0; i < N; ++i) {
array[i] = userinput_integer("%d: ", i);
}
return N;
}
void print_arrayelements(int *array, int N){
for(int i = 0; i < N; ++i) {
printf("%d ", array[i]);
}
}
int main() {
int N, *array;
N = userinput_arraylength();
array = malloc(N * sizeof(*array));
if (NULL == array){
printf("Allocation error!\n");
exit(-1);
}
N = userinput_arrayelements(array, N);
printf("Array length is: %d \n", N);
printf("Elements of array are:\n");
print_arrayelements(array, N);
free(array);
return 0;
}
Fistly, declaration of array is not correct.
It should be array[] = {0}
Secondly, you cannot call your array elements function before arrayN function, the size of array should be entered first
And in the array elements() there is no need to call the size function you can directly pass the size of array when calling the array elements ()
Here's the code:
#include <stdio.h>
#include<malloc.h>
int *getarray()
{
int size;
printf("Enter the size of the array : ");
scanf("%d",&size);
int *p= malloc(sizeof(size));
printf("\nEnter the elements in an array");
for(int i=0;i<size;i++)
{
scanf("%d",&p[i]);
}
return p;
}
int main()
{
int *ptr;
ptr=getarray();
int length=sizeof(*ptr);
printf("Elements that you have entered are : ");
for(int i=0;ptr[i]!='\0';i++)
{
printf("%d ", ptr[i]);
}
return 0;
}
I am taking a number in the main function, make it an array in make_array function. In the palindrome function, I need to check the array which i made in the make_array function but it is not visible in the palindrome function.
How can I solve this problem?
#include<stdio.h>
#define N 5
void make_array(int n);
int palindrome(int ar[],int size);
int main()
{
int num;
printf("Enter a number to check: ");scanf("%d",&num);
make_array(num);
if(palindrome(/*Don't know what should I write here*/))
printf("It is palindrome");
else
printf("It is not palindrome");
}
void make_array(int n)
{
int arr[N];
int digit,i=0;
while(n>0){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
}
int palindrome(int ar[],int size)
{
int i,j;
int temp[N];
j=N;
for(i=0; i<N; i++)
temp[i]=ar[i];
for(i=0; i<N; i++){
if(temp[j-1]!=ar[i])
return 0;
j--;
}
return 1;
}
The best way is to leave allocation to the caller. Then you can simply do
int main()
{
int num;
printf("Enter a number to check: ");scanf("%d",&num);
int array[num];
fill_array(num, array);
where fill_array does what "make_array" does in your code, minus the allocation part.
void fill_array(int num, int array[num]);
The palindrome function could be rewritten similarly:
int palindrome(int size, int array[size])
All of this uses the concept of variable-length arrays (VLA).
I have done some modification in your code so please refer it.
#include<stdio.h>
#include "stdafx.h"
#define N 5
int make_array(int n, int *arr);
int palindrome(int ar[],int size);
int main()
{
int num;
int arr[N];
int iRet;
printf("Enter a number to check: ");scanf_s("%d",&num);
iRet = make_array(num, arr);
if(palindrome(arr, iRet))
printf("It is palindrome");
else
printf("It is not palindrome");
}
int make_array(int n, int *arr)
{
//int arr[N];
int digit,i=0;
while(n>0){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(int j=0; j<i; j++)
printf("%d ",arr[j]);
return i;
}
int palindrome(int ar[],int size)
{
int i,j;
int temp[N];
j=size;
for(i=0; i<size; i++)
temp[i]=ar[i];
for(i=0; i<size; i++){
if(temp[j-1]!=ar[i])
return 0;
j--;
}
return 1;
}
The problem is with your make array function. When a function is called, the stack grows down and registers and pointers are allocated to save the point from which that function was called, now, here you send n by value and your function creates a place on the stack for an array that you fill- BUT- when your function returns- the stack pointer returns back up to the caller( if your function has a return value it will be saved in a pre-allocated place, but other than that all of the other function data on stack is unavailable.).
So in general, if you want a function to create an array that could be used later on it must be allocated on heap you can either return int* or send foo(int**) to the function that will hold the add. of the new allocated array.
another option is to allocate that array[N] in your main, and send foo(int arr[], int n, size_t size) to the function. Since the array was allocated by the caller in main- this memory will be valid for all of the main function life.
so option 1)
int main()
{
int num;
int* array;
printf("Enter a number to check: ");scanf("%d",&num);
array = make_array(num, N);
if(palindrome(array, N))
printf("It is palindrome");
else
printf("It is not palindrome");
free(array); /*free heap allocation */
}
int* make_array(int n, size_t size)
{
int* arr;
int digit ,i=0;
arr = malloc(sizeof(int)*size);
if(NULL == arr)
{
return NULL; /* malloc failed*/
}
while(n>0 && i<size){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
return arr;
}
or 2)
int main()
{
int num;
int array[N];/*array saved on stack in main function */
printf("Enter a number to check: ");scanf("%d",&num);
make_array(array,num, N);
if(palindrome(/*Don't know what should I write here*/))
printf("It is palindrome");
else
printf("It is not palindrome");
}
void make_array(int* arr, int n, size_t size)
{
int digit,i=0;
if(NULL == arr)/*if arr is not a valid pointer*/
{
return;
}
while(n>0 && i<size){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
}
I am trying to write a recursive function in C,
Given an array, size of the array as well as the element int target, I want to find the index of int target's last occurence.
#include <stdio.h>
int rLookupAr(int array[], int size, int target);
int main()
{
int numArray[80];
int target, i, size;
printf("Enter array size: \n");
scanf("%d", &size);
printf("Enter %d numbers: \n", size);
for (i=0; i < size; i++)
scanf("%d", &numArray[i]);
printf("Enter the target number: \n");
scanf("%d", &target);
printf("rLookupAr(): %d", rLookupAr(numArray, size, target));
return 0;
}
int rLookupAr(int array[], int size, int target)
{
}
However, I have been stuck for hours.
I am a beginner to recursive functions and any help will be greatly appreciated!
Some examples:
Enter array size:
5
Enter 5 numbers:
2 1 3 2 4
Enter the target number:
2
rLookupAr(): 3
If you're after the last occurrence, then you can start your search at the end of the array and work backwards.
C arrays are referenced by a pointer to any element and a length or index upper-bound value, which you have.
One way of looking at recursive functions is asking "is each step of the algorithm just repeating the whole thing, just on a decreasing subset of the input data?" - consider problems like processing trees (where each child node is a tree itself) or operations like quicksort (where each pivot gives you two more sub-sections which you pivot again, and so on).
Consider that finding a value in an array of [0...N] is the same as finding the value by checking [0] and then checking [1...N], then repeating yourself all over again by checking [1] and then checking [2..N]...hopefully you're seeing a pattern emerging.
For working backwards, given the array's start and length N, you'd check [N] first, then repeat with the range [0..(N-1)], then check [N-1] then repeat with [0...(N-2)].
I hope that will enable you to come to a solution without me just giving you the answer.
You can define rLookupAr() function as following. See the complete working code here:
int rLookupAr(int array[], int size, int target)
{
if(size < 1) return -1;
size--;
if(array[size] == target) return size;
return rLookupAr(array, size,target);
}
Note: rLookupAr() function will return -1 if target value is not found in array array.
OUTPUT:
Enter array size: 5
Enter 5 numbers: 2 1 3 2 4
Enter the target number: 2
rLookupAr(): 3
Following is the complete code:
#include <stdio.h>
int rLookupAr(int array[], int size, int target);
int main()
{
int numArray[80];
int target, i, size;
printf("Enter array size: \n");
scanf("%d", &size);
printf("Enter %d numbers: \n", size);
for (i=0; i < size; i++)
scanf("%d", &numArray[i]);
printf("Enter the target number: \n");
scanf("%d", &target);
printf("rLookupAr(): %d", rLookupAr(numArray, size, target));
return 0;
}
int rLookupAr(int array[], int size, int target)
{
if(size < 1) return -1;
size--;
if(array[size] == target) return size;
return rLookupAr(array, size,target);
}
Please find the recursive function below:
int rLookupAr (int array[], int size, int target)
{
if(size<=0) return -1;
if(array[size-1] == target)
return size-1;
else
return rLookupAr (array, size-1, target); //recurse
}
basically the functions starts from the end because the last occurance is being sought. Depending on whether the target is found or not it further recurses down the array.
Complete code:
#include <stdio.h>
int rLookupAr (int array[], int size, int target);
int
main ()
{
int numArray[80];
int target, i, size;
printf ("Enter array size: \n");
scanf ("%d", &size);
printf ("Enter %d numbers: \n", size);
for (i = 0; i < size; i++)
scanf ("%d", &numArray[i]);
printf ("Enter the target number: \n");
scanf ("%d", &target);
printf ("rLookupAr(): %d", rLookupAr (numArray, size, target));
return 0;
}
int
rLookupAr (int array[], int size, int target)
{
if(size<=0) return -1;
if(array[size-1] == target)
return size-1;
else
return rLookupAr (array, size-1, target); //recurse
}
Output:
Enter array size:
5
Enter 5 numbers:
2
1
3
2
4
Enter the target number:
2
rLookupAr(): 3
Here is a solution with a single statement:
int rLookupAr(int array[], int size, int target) {
return size-- <= 0 ? -1 : array[size] == target ? size : rLookup(array, size, target);
}
Using a recursive solution for a simple case like this is only meant as an exercise. C compilers are not required to perform tail recursion optimization to convert this code to a loop, so this recursive implementation can easily cause a stack overflow for a moderately large array.
I am a beginner to recursive functions
Recursive functions get a bad name with linear reduction.
Instead break the problem in 2 to achieve a a recursive depth of log2(n).
int rLookupAr(int array[], int size, int target) {
if (size < 1) {
return -1;
}
int mid = size/2;
int right = rLookupAr(array + mid, size - mid, target);
if (right != -1) {
return right + mid;
}
int left = rLookupAr(array, mid, target);
return left;
}
int rLookupAr(int input[], int size, int x) {
/* Don't write main().
Don't read input, it is passed as function argument.
Return output and don't print it.
Taking input and printing output is handled automatically.
*/
if(size==0)
{
return -1;
}
//return -1;
int ans=lastIndex(input+1,size-1,x);
if(ans!=-1)
{
return ans+1;
}
else{
if(input[0]==x)
{
return ans+1;
}
else
{
return -1;
}
}
}
int lastIndex(int input[], int size, int x)
{
if (size == 0)
{
return -1;
}
int answer = lastIndex(input + 1, size - 1, x);
if (answer != -1)
{
return answer + 1;
}
if (input[0] == x)
{
return 0;
}
else
{
return -1;
}
}
int main()
{
int input[] = {9, 8, 10, 8};
int x = 8;
int size = 4;
cout << lastIndex(input, size, x);
return 0;
}
This code is supposed to recieve to arrays and then call function to return them in 1 array but I don't know how to print the last array returned from the function thanks in advance ???
and now I write anything because it says that the post is mostly code :D :D
#include <stdio.h>
#include <stdlib.h>
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size);
int main() {
int size_arr1, size_arr2, i, num1 = 1, s;
printf("Please enter the size of the first array: ");
scanf("%d", &size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for (i = 0; i < size_arr1; i++) {
printf("enter element number %d: ",num1);
scanf("%d", &arr1[i]);
num1++;
}
num1 = 1;
printf("Please enter the size of the second array: ");
scanf("%d", &size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for (i = 0; i < size_arr2; i++) {
printf("enter element number %d: ", num1);
scanf("%d", &arr2[i]);
num1++;
}
ptr1_last = join_arrays(arr1, arr2, size_arr1, size_arr2);
printf("sorted array= \n");
for (s = 0; s < (size_arr1 + size_arr2); s++) {
printf("%d\n", ptr1_last);
}
return 0;
}
int join_arrays(int *array1, int *array2, int arr1_size, int arr2_size) {
int counter_arr1, counter_arr2, m = 0;
int last_arr[arr1_size + arr2_size];
for (counter_arr1 = 0; counter_arr1 < arr1_size; counter_arr1++) {
last_arr[counter_arr1]=array1[counter_arr1];
}
for (counter_arr2 = counter_arr1; counter_arr2 < (arr1_size + arr2_size); counter_arr2++) {
last_arr[counter_arr2] = array2[m];
m++;
}
return last_arr[0];
}
Modified the code to create the receiving array in main and pass a pointer to it to the merge function because the local array last_arr would no longer exist when the function returned in your code.
#include <stdio.h>
#include <stdlib.h>
//Prototype changed to include a pointer to the receiving array, also no longer returns a value.
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size);
int main()
{
int size_arr1,size_arr2,i,num1=1,s;
printf("Please enter the size of the first array: ");
scanf("%d",&size_arr1);
int arr1[size_arr1];
printf("start fill your first array: \n");
for(i=0; i<size_arr1; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr1[i]);
num1++;
}
num1=1;
printf("Please enter the size of the second array: ");
scanf("%d",&size_arr2);
int arr2[size_arr2];
int *ptr1_last;
printf("start fill your second array: \n");
for(i=0; i<size_arr2; i++)
{
printf("enter element number %d: ",num1);
scanf("%d",&arr2[i]);
num1++;
}
int last_arr[size_arr1 + size_arr2]; //Create receiving array here
join_arrays(last_arr, arr1,arr2,size_arr1,size_arr2); //And pass it to the function.
printf("merged array= \n");
for(s=0;s<(size_arr1+size_arr2);s++)
{
printf("%d\n", last_arr[s]);
}
return 0;
}
void join_arrays(int *last_arr, int *array1,int *array2,int arr1_size,int arr2_size)
{
int counter_arr1, m=0;
for(counter_arr1=0; counter_arr1<arr1_size; counter_arr1++)
{
last_arr[counter_arr1]=array1[counter_arr1];
}
for(; counter_arr1<(arr1_size+arr2_size); counter_arr1++)
{
last_arr[counter_arr1]=array2[m];
m++;
}
}
With that function you return only the first element of the last_array, you should create a global array so it's visible in all functions, or return a pointer of the last_array[0] position in memory