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]);
}
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 wrote a program to get an array which will return an array with elements as difference between max value and remaining elements.
#include <stdio.h>
void behind(int *, int);
int main(void) {
int array[10];
int N, i;
scanf("%d", &N);
for (i=0; i<N; i++) {
scanf("%d", &array[i]);
}
behind(array, N);
for (i=0; i<N; i++) {
printf("%d\n", array[i]);
}
return 0;
}
void behind(int *ptr,int size) /* Write your function behind() here: */
{
int i,max=0;
for(i=1;i<size;i++){
if(ptr[i-1]>=ptr[i])
max=ptr[i-1];
else
max = ptr[i];
}
for(i=0;i<size;i++);
ptr[i]=max-ptr[i];
}
why my program always return the same array that I got as input?
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;
}
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.
I'm writing a code for my C programming class and stumbled upon a problem. I'm supposed to write a program which will show as an output Pascal's triangle. I'm to use 1d arrays and in each iteration make the array bigger by using realloc. The trouble is that even though the code compiles and runs when I type eg '7' (as the height of the tringle) in the 7th column there will be trash number. I have no idea why it happens. I'm a beginner in dynamic memory allocation, so please by gentle.
Here's my code:
int i,n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = (int*)malloc(sizeof(int));
int *tab2, liczba=2;
for(i=0;i<n;i++)
{
tab2=(int *)realloc(tab,i+1);
tab2[i]=&liczba;
print(tab2, i+1);
printf("\n");
}
void print(int *tab, int size)
{
int i;
for(i=0;i<size;i++) printf("%d\t", tab[i]);
}
#include <stdio.h>
#include <stdlib.h>
void print(int *tab, int size);
int main(void){
int i, j, n;
printf("Give the height:\n");
scanf("%d", &n);
int *tab = NULL;
for(i=1;i<=n;++i){
int *temp = realloc(tab, i * sizeof(*tab));
if(temp)
tab = temp;
else {
perror("realloc");
free(tab);
exit(EXIT_FAILURE);
}
tab[i-1] = (i == 1) ? 1 : 0;
for(j=i-1;j>0;--j){
tab[j] += tab[j-1];
}
print(tab, i);
}
free(tab);
return 0;
}
void print(int *tab, int size){
int i;
for(i=0;i<size;i++){
if(i)
putchar('\t');
printf("%d", tab[i]);
}
putchar('\n');
}