Issues with pascal triangle and dynamic memory allocation, c - c

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');
}

Related

Error in User defined size for array in c

*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);
}

Finding specific sum of a integers in an array

Basically this problem asks me to get an input of target_sum and check the integers in the array. If a sum of a pair is equal to target_sum, I need to print it.
I wrote the code like this but it does not work. Where did I make the mistake?
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++){
for (j=0;j<size;j++){
if (arr[i] + arr[j] == target_sum)
{
printf("(%d,%d)",arr[i],arr[j]);
}
else
{
printf("No pair.");
}
}
}
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",target_sum);
findPair(arr,6,target_sum);
}
As #nsilent22 suggested, scanf("%d",target_sum); should be changed into scanf("%d",&target_sum);. Besides that, you could have the second for loop start at j=i+1, making your code overall look like this:
#include <stdio.h>
void findPair (int arr[],int size,int target_sum)
{
int i,j;
for (i=0;i<size;i++)
for (j=i+1;j<size;j++)
if (arr[i] + arr[j] == target_sum)
printf("\n(%d,%d)",arr[i],arr[j]);
else
printf("\nNo pair.");
}
int main(){
int arr[] = {8,7,2,5,3,1};
int target_sum;
printf("Enter target sum: ");
scanf("%d",&target_sum);
findPair(arr,6,target_sum);
}

I want to make a program in C which takes an array as an input and tells which number are perfect squares

#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.

How to pass arrays to a function in C

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]);
}

create Pascal triangle in c

I try to make a pascal triangle of n rows and I have to make a fucntion for allocate memory for the matrix, a function to print and free memory I think I have a lot of trouble in my code
in the function build I try to allocate the memory for the matrix and charge it i use a function full for chage the matrix, I think my principal problem is that I have an irregular matrix I don't know how to procede, maybe make an array of arrays or somthing like that could be better, sorry for my english
int main()
{
int **triangle=NULL;
int n;
printf("size of triangle");
scanf("%d",&n);
build(&triangle,n);
print(triangle,n);
return 0;
}
void build(int***triangle,int n){
*triangle=(int**)calloc(n,sizeof(int*));
int i;
for(i=0;i<n;i++){
*(triangle)[i]=(int*)calloc(i+1,sizeof(int));
}
full(*triangle,n);
}
void full(int**triangle,int n){
int i;
int j;
for(i=0;i<n;i++){
for(j=0;j<i;j++){
if(j==0){
triangle[i][j]=1;
}
else
if(j==i){
triangle[i][j]=1;
}
else
triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
}
}
}
void print(int **triangle,int n){
int i;
int j;
for(i=0;i<n;i++){
for(j=0;j<i;j++){
printf("%d",triangle[i][j]);
}
}
}
*(triangle)[i]=(int*)calloc(i+1,sizeof(int));
should be
(* triangle)[i]=(int*)calloc(i+1,sizeof(int));

Resources