I can not allocate memory in an array - c

#include<stdio.h>
#include<stdlib.h>
int crp(int mtrs[],int size)
{
int a=1;
int i;
for(i=0;i<size;++i)
{
a*=mtrs[i];
}
return a;
}
int main()
{
int k,size;
int **mtrs;
printf("enter the size of the matrix:");
scanf("%d",&size);
mtrs=(int**)malloc(size*sizeof(int*));
if( mtrs == NULL )
printf( "Yetersiz bellek!" );
printf("enter the input numbers of matrix:");
for(k=0;k<size;k++)
{
mtrs[k] =(int*) malloc( size* sizeof(int) );
if( mtrs[k] == NULL )
printf( "not enough memory!" );
}
for(k=0;k<size;k++)
{
scanf("%d",&mtrs[k]);
}
printf("\n\n");
for(k=0;k<size;k++){
printf("%d ",mtrs[k]);
}
printf("\n\n");
printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size));
return 0;
}
I get the problem of access violation reading location 0xFDFDFD.
it stucks at the location of a*=mtrs[i];.. The program's aim is to multiplication of the entered numbers
I am not sure if I am using the malloc in a correct way.

This code snippet is invalid
for(k=0;k<size;k++)
{
scanf("%d",&mtrs[k]);
&&&&&&&&
}
You should write for example
int m;
//...
for(k=0;k<size;k++)
{
for ( m = 0; m < size; m++ )
{
scanf("%d", &mtrs[k][m]);
}
}
The same is valid for this loop
for(k=0;k<size;k++){
printf("%d ",mtrs[k]);
}
It should look like
for(k=0;k<size;k++)
{
for ( m = 0; m < size; m++ )
{
printf("%d ",mtrs[k][m]);
}
printf( "\n" );
}
The function should be defined like
long long int crp( int * mtrs[],int size)
^^^^^^^^^^^^^ ^^^^^^^^^^^^
{
long long int a=1;
int i, j;
^^^^^^^^^
for(i=0;i<size;++i)
{
for ( j = 0; j < size; j++ )
{
a*=mtrs[i];
}
}
return a;
}
And the result of the function should be outputted like
printf("Elemanlar carpimi %lld dir.",crp(mtrs,size));
^^^^^

I do not fully understand what is your code point, but you have various mistakes and logic problems with it.
printf("%d ",mtrs[k]); and scanf("%d",&mtrs[k]); expect int but you passed *int (aka int[]), you probably need to insert/read values using 2 nested for loops.
printf("Elemanlar carpimi %d dir.",crp(mtrs[k],size)); last cycle is for(k=0;k<size;k++), according to it k = size, so mtrs[k] is out of bounds, which cause application crash.

Related

Numbers aren't showing up right

Hello there!
I'm kind of confused , I literally tried every possible sollution i could think of.
Yet the program isn't functioning right ! The purpose of this program is to seperate the odd numbers and the pair numbers from one single array and put each one of them on an array!
When i execute , and after putting some simple numbers , another random big numbers appear in each array!
why is that and how can i fix this ?
void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j=0;
for (i=0;i<*n;i++){
if(T[i]%2==0){
P[j]=T[i];
j++;}
else{
Imp[j]=T[i];
j++;
}}
*n=j;
}
int main(){
int t[100],p[100],imp[100];
int n;
puts("saisir n :");
scanf("%d",&n);
puts("saisir le tableau : ");
int i;
for(i=0;i<n;i++){
scanf("%d",&t[i]);
}
for(i=0;i<n;i++){
printf("%d ",t[i]);
}
Pairs_impairs(&n,t,p,imp);
printf("\nLes pairs : ");
for(i=0;i<n;i++){
printf("%d ",p[i]);
}
printf("\nLes impairs : ");
for(i=0;i<n;i++){
printf("%d ",imp[i]);
}
return 0;
}
The function is incorrect. You need to keep separate indices for the arrays P and Imp within the function. For example
void Pairs_impairs(int* n,int T[], int P[], int Imp[]){
int i,j1=0, j2 = 0;
for (i=0;i<*n;i++){
if(T[i]%2==0){
P[j1]=T[i];
j1++;}
else{
Imp[j2]=T[i];
j2++;
}}
*n=j1;
}
Also you should guarantee that the both arrays P and Imp will have equal number of elements. Otherwise you need to return from the function two indices.
For example
struct Pair
{
size_t first;
size_t second;
};
struct Pair Pairs_impairs( const int T[], size_t n, int P[], int Imp[] )
{
struct Pair p = { .first = 0, .second = 0 };
for ( size_t i = 0; i < n; i++ )
{
if ( T[i] % 2 == 0 )
{
P[first++] = T[i];
}
else
{
Imp[second++] = T[i];
}
}
return p;
}

I want Print an array in reverse but it is not printing all the elements of the array

#include <stdio.h>
int main()
{
int a,n,i;
int arr[n];
// int arr[]={1,4,3,2};
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(int i=n;i>=0;i--)
{
printf("%d ",arr[i]);
}
}
Thanks guys for helping in that but now what could be the error its showing garbage value.
For the defined array
int arr[]={1,4,3,2};
in this for loop
for(int i=3;i>=arr[0];i--)
i equal to 0 is not greater than or equal to arr[0] equal to 1. So the condition of the loop i>=arr[0] evaluates to logical false when i is equal to 0.
Maybe actually you mean the following loop
for(int i=3;i >=0;i--)
Pay attention to that it is not a good idea to use magic numbers like 3.
You could define the loop the following way
for ( size_t i = sizeof( arr ) / sizeof( *arr ); i != 0; --i )
{
printf( "%d ", arr[i - 1] );
}
or
for ( size_t i = sizeof( arr ) / sizeof( *arr ); i != 0; )
{
printf( "%d ", arr[--i] );
}
Also in your commented statements are placed in a wrong order
int a,n;
//int arr[n];
//scanf("%d",&n);
At first you need to read a positive value in the variable n and only after that to declare the variable length array arr
int a,n;
scanf("%d",&n);
int arr[n];
Here is a demonstrative program.
#include <stdio.h>
int main(void)
{
size_t n;
if ( scanf( "%zu", &n ) == 1 && n != 0 )
{
int arr[n];
for ( size_t i = 0; i < n; i++ )
{
scanf( "%d", arr + i );
}
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", arr[i] );
}
putchar( '\n' );
for ( size_t i = n; i != 0; i-- )
{
printf( "%d ", arr[i-1] );
}
putchar( '\n' );
}
return 0;
}
If to enter the following values
5
1 2 3 4 5
then the program output will be
1 2 3 4 5
5 4 3 2 1
As arr[0] contains 1 your code will only print arr[3], arr[2] and arr[1].
You can do something like:
int main ()
{
int a, n;
//int arr[n];
int arr[] = { 1, 4, 3, 2 };
//scanf("%d",&n);
for (int i = sizeof (arr) / sizeof (arr[0]) - 1; i >= 0; i--)
{
printf ("%d ", arr[i]);
}
}
sizeof gives size of type (for int in c size is 4)
so you can divide it by any one element of the array
then your iterator variable i's value is also dynamic.
Need to tweak condition in for loop to i = n -1 while printing reverse array.
You are getting garbage values because your second for loop tries to print arr[n] which is out of bounds. Array indexing goes from 0 to n-1 where n is the size of the array. Ref
Here is the corrected code.
#include <stdio.h>
int main()
{
int a,n,i;
int arr[n];
// int arr[]={1,4,3,2};
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(int i=n;i>0;i--)
{
printf("%d ",arr[i-1]);
}
return 0;
}

Functions and arrays which allows you to print what's the most repeated number

I have a problem with my code, it doesn't print the result I expect. This code allows the user to enter as many numbers as he wishes and then print the most repeated one
Here it is:
#include <stdio.h>
void reading_numbers(int array[]){
int i = 0;
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
while (i < Max) {
printf("Insert the numbers\n");
scanf("%d", &array[i]);
i++;
}
}
void most_present_number(int array[], int Max){
int i = 0;
reading_numbers(array);
int current_number = array[i];
int current_number_count = 0;
int most_present_one = 0;
int most_present_one_counter = 0;
while (i < Max) {
if (array[i] == current_number) {
current_number_count++;
i++;
} else {
if (current_number_count > most_present_one_counter){
most_present_one = current_number;
most_present_one_counter = current_number_count;
}
current_number_count = 1;
}
}
printf("This is the most present number %d it is repeated %d times\n", most_present_one,
most_present_one_counter);
}
int main() {
int Max = 0;
int array[Max];
most_present_number(array, Max);
return 0;
}
The problem for me is when I call the function, but I don't know how to fix it
I should have written as a premise but I'm a bit new to C so probably there are some things in this code that don't make sense
I make a procedure to find the result ,int main() must have the size of array (mistake logic),because the procedure take the parameters of the main function (int main ())
Here is my code:
#include<stdio.h>
void most_present_number(int Max,int T[Max])
{
int i = 0;
while (i < Max)
{
printf("Insert the numbers :");
scanf("%d", &T[i]);
i++;
}
int k=0,cpt1=0,cpt=0;
for(int i=0;i<Max;i++)
{
cpt=0;
for(int j=i+1;j<Max;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>=cpt1)
{
cpt1=cpt;
k=T[i];
}
}
printf("This is the most present number %d it is repeated %d times\n",k,cpt1+1);
}
int main()
{
int Max = 0;
do
{
printf("How much long the array will be?\n");
scanf("%d", &Max);
}while(Max<1);
int T[Max];
most_present_number(Max,T);
}
the following proposed code:
cleanly compiles
performs the desired functionality
only includes header files those contents are actually used
and now the proposed code:
#include <stdio.h>
void reading_numbers( int Max, int array[ Max ][2])
{
for( int i = 0; i < Max; i++ )
{
printf("Insert the numbers\n");
scanf("%d", &array[i][0]);
array[i][1] = 0;
}
}
void most_present_number( int Max, int array[ Max ][2] )
{
for( int i=0; i < Max; i++ )
{
for( int j=i; j<Max; j++ )
{
if ( array[i][0] == array[j][0] )
{
array[i][1]++;
}
}
}
int most_present_one = array[0][0];
int most_present_one_counter = array[0][1];
for( int i=1; i<Max; i++ )
{
if( most_present_one_counter < array[i][1] )
{
most_present_one = array[i][0];
most_present_one_counter = array[i][1];
}
}
printf("This is the most present number %d it is repeated %d times\n",
most_present_one,
most_present_one_counter);
}
int main( void )
{
int Max = 0;
printf("How much long the array will be?\n");
scanf("%d", &Max);
int array[Max][2]; // uses variable length array feature of C
reading_numbers( Max, array );
most_present_number( Max, array );
return 0;
}
a typical run of the code:
How much long the array will be?
4
Insert the numbers
1
Insert the numbers
2
Insert the numbers
3
Insert the numbers
2
This is the most present number 2 it is repeated 2 times

Why does this program crashes on execution?

I am trying to run this code on Dev C++ but it keeps on crashing after the user inputs the two numbers. The program takes input m and n from user two numbers and then returns the output as the solution of the function A which is:
A(m,n) = A(m,n-1)+ A(m-1, n) , if m,n >0
A(m,n) = m-n if m or n <0
Can anybody please tell me why is it happening?
#include<stdio.h>
#include<stdlib.h>
int main() {
int num1=0;
int num2=0;
int rows=0;
int columns=0;
int i,j,**array;
printf("Enter two non-negative integer numbers \n");
scanf("%d %d",&num1,&num2);
//create 2d-Array
rows=num1+1;
columns=num2+1;
array=malloc(rows * sizeof(int *));
for(i=0;i<rows;i++)
{
array[i]=malloc(columns*sizeof(int));
}
//Fill data in array
computeArray(array,rows,columns);
// Display contents of array
for (i = 0; i < rows; i++ )
{
for(j= 0; j < columns; j++ )
{
printf("array[%d][%d] = %d\n", i,j, array[i][j] );
}
}
getch();
return 0;
}
int computeArray (int **array, int rows, int columns) {
int i,j;
for(i=0; i<rows;i++)
{
for(j=0;j<columns;j++)
{
array[i][j]=computeFunction(array,i,j);
}
}
return **array;
}
int computeFunction(int **array, int i, int j) {
int value=0;
if((i<0)||(j <0))
{
value = i-j;
printf("%d",value);
return value;
}
else
{
value = (array[i][j-1] + array[i-1][j]);
printf("%d",value);
return value;
}
return value;
}
When program's behavior is undefined, anything could happen. You should declare a prototype for the function computeArray and computeFunction before main:
int computeArray (int **array, int rows, int columns);
int computeFunction(int **array, int i, int j);
and change
if((i<0)||(j <0)) {...}
in computeFunction to
if((i<=0) || (j <= 0)){...}
&& instead of || may help.
The code fails at the
value = (array[i][j-1] + array[i-1][j]);
line, when j==0.
Debuggers tend to be very useful for spotting simple mistakes. Use them.

Generating an array of integers

I got a problem in generating an array of integers. the program fills hundreds of cells of the array with numbers like -32429173 instead of 3 cells with numbers from 0 to 3 (for example). Maybe the problem is in the wrong way of allocating memory? Here is the wrong part of the code. Thx for the help in advance.
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
Here is the full code
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
int size;
void swap(int* elem1,int* elem2) //swap elements
{
int temp;
temp=*elem1;
*elem1=*elem2;
*elem2=temp;
}
void bublesort(int* array,int size) //bublesort
{
for (int j=1;j<size-1;++j)
{
for (int i=0;i<size-j;++i)
{
if ((array[i])>(array[i+1]))
swap(&array[i],&array[i+1]);
}
}
}
int* enterHand() //handle entering
{
int i;
scanf_s("%d",&size);
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
{
scanf_s("%d",&array[i]);
}
return array;
}
int* enterFile() //entering from the file
{
int i;
int singlenumb;
FILE* foo;
errno_t err;
err=fopen_s(&foo,"input.txt","r");
if( err == 0 )
{
printf( "The file 'input.txt' was opened\n" );
}
else
{
printf( "The file 'input.txt' was not opened\n" );
}
while (!feof(foo))
{
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
int* array=(int*)calloc(size,sizeof(int));
rewind(foo);
i=0;
while (i!=size)
{
fscanf_s(foo, "%d", &array[i]);
i++;
}
fclose(foo);
return array;
}
int* generate()
{
int maxnumb;
int i;
scanf_s("%d",&size); //size of an array
scanf_s("%d",&maxnumb); //asks for maxnumb to fill the array with random numbers from 0 to maxnumb
int* array=(int*)calloc(size,sizeof(int));
for (i=0;i<size;i++)
array[i] = rand() % maxnumb + 1;
return array;
}
void putsFile(int* array, int size)
{
int i=0;
int k;
FILE* fooo;
fopen_s(&fooo,"output.txt","w");
while (i!=size)
{
for (k=0; k<10; k++)
{
fprintf(fooo,"%d ", array[i]);
i++;
}
fprintf(fooo,"\n");
}
fclose(fooo);
}
void printArray(int* array, int size)
{
int i=0;
int k;
while (i!=size)
{
for (k=0; k<10; k++)
{
printf("%d ", array[i]);
i++;
}
printf("\n");
}
}
int main()
{
int choice;
int* pntr;
printf("choose a type of filling an array\n1 = handle filling\n2 = filling from the file\n3 = generating\nenter the number...\n");
scanf("%d", &choice);
switch (choice)
{
case 1: {pntr=enterHand();} break;
case 2: {pntr=enterFile();} break;
case 3: {pntr=generate();} break;
default: {pntr=NULL;}
}
bublesort(pntr,size);
printf("choose a type of typing an array\n1 = console\n2 = file\nenter the number...\n");
scanf("%d", choice);
switch (choice)
{
case 1: {printArray(pntr, size);} break;
case 2: {putsFile(pntr, size);} break;
default: {printf("you entered the wrong number");}
}
return 0;
}
I think you should initialize your maxnumb
First, here is a simpler approach for filling an array.
int randomGenerator(int min, int max);
int main(void)
{
int array[100]//or any size
for(i=0;i<sizeof(array)/sizeof(array[0]);i++)
{
array[i]=randomGenerator(1,3);//will issue only 1, 2 or three (as you requested)
} //change min and max for wider range
return 0;
}
int randomGenerator(int min, int max) //set the range of desired numbers in array
{
int random=0, trying=0;
trying = 1;
while(trying)
{
srand(clock());
random = (rand()/32767.0)*(max+1);
(random >= min) ? (trying = 0) : (trying = 1);
}
return random;
}
There are also some things you can do to make this non-repeating, i.e. so you won't get two Ace of Spades. But for now, you have much bigger issues...
Your code, as is has too many issues to build. If you post a small, buildable section, with the specific problem, it can be better addressed.
The printArray() and putsFile() may print outside array size.
int* enterFile() does not set size to 0 before determining number of int in the file, thus using a potentially unexpected non-zero size.
[Edit] Well size is implicitly set to 0 being in the global uninitialized space. Still, recommend explicitly setting to 0 in enterFile().
#if 0
// The value of size is dependent on program history or uninitialized.
while (!feof(foo)) {
fscanf_s(foo, "%d", &singlenumb);
size++;
}
size-=1;
#else
size = 0; // Reset size to 0
while (1 == fscanf_s(foo, "%d", &singlenumb)) {
size++;
}
#endif
Suggest:
void printArray(int* array, int size) {
// Also in void putsFile(int* array, int size)
int i=0;
while (i < size) {
int k;
for (k=0; k<10; k++) {
printf("%d ", array[i]);
i++;
// Add
if (i >= size) break;
}
printf("\n");
}
}

Resources