how to put numbers from interval to array? (C language) - c

I am looking for this for a while.
Can anyone tell me how can I create interval array?
Example:
interval = < 4;9 >
int array[9-4+1] = {4,5,6,7,8,9}
I would like to insert number from interval to array and than I can work with values in array.
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int size_Of_Interval;
int a;
int b;
printf("Please specify the starting interval value: ");
scanf("%d", &a);
printf("Please specify the ending interval value: ");
scanf("%d", &b);
size_Of_Interval = (b-a+1);
printf("Interval from %d to %d. Interval has %d numbers\n", a, b, size_Of_Interval);
return 0;
}

If your compiler supports variable length arrays (VLAs) then you can just write
int arr[size_Of_Interval];
for ( int i = 0; i < size_Of_Interval; i++ )
{
arr[i] = a + i;
}
Otherwise you should dynamically allocate an array. For example
int *arr = malloc( size_Of_Interval * sizeof( int ) );
for ( int i = 0; i < size_Of_Interval; i++ )
{
arr[i] = a + i;
}
In this case you will need also to free the array when it will not be needed any more
free( arr );

Before to return from the main:
int *array = malloc(size_of_interval * sizeof(int));
This dynamically allocates the needed amount of memory, returning a pointer to the firts element of an array with size_of_interval length. Afterward you can go through a loop and fill that array:
for(int i = 0; i < size_Of_Interval; i++) {
array[i] = a + i;
}
When you end the job with your array, as commented above, you need to free the resource:
free(array);

Related

multi pointers in function in c

i'm not good at english.
i declare array and two pointers.
the maxPtr pointer should have array arr's maximum number adress.
and minPtr pointer should have array arr's minimum number adress.
so i declare the function and this has two double-pointer to give maxPtr and minPtr proper adress.
but whenever i run this code, the program is not fully run.
it doesn't output the result( printf("%d",*maxPtr) ,printf("%d", *minPtr, printf("Hi");
this program is run at vscode in mac.
what make it error?
#include <stdio.h>
void MaxAndMin(int* str,int** max, int** min)
{
int i;
int maxnum=0,minnum=0;
for(i=0; i<5; i++)
{
if(maxnum< str[i])
{
maxnum =str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
}
int main(void)
{
int i,len;
int* maxPtr;
int* minPtr;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("%d번째 정수입력 입니다.",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr,&maxPtr,&minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}
the result is
> Executing task: ./test <
1번째 정수입력 입니다.1
2번째 정수입력 입니다.2
3번째 정수입력 입니다.3
4번째 정수입력 입니다.4
5번째 정수입력 입니다.5
Terminal will be reused by tasks, press any key to close it.
For starters this initialization of an array
int arr[5]={};
is incorrect in C. You have to write
int arr[5]={ 0 };
Secondly using the magic number 5 within the function makes the function useless in general. You need to pass to the function the size of the array.
The initial value 0
int maxnum=0,minnum=0;
of these variables makes the function even more less useful. In general the array can contain either all elements positive or all elements negative.
And you need to flush the output buffer using for example the new line character '\n' in calls of printf.
The function can be declared and defined the following way as it is shown in the demonstration program below.
#include <stdio.h>
void MaxAndMin( const int a[], size_t n, int **max, int **min )
{
*max = ( int * )a;
*min = ( int * )a;
for ( size_t i = 1; i < n; i++ )
{
if ( **max < a[i] )
{
*max = ( int *)( a + i );
}
else if ( a[i] < **min )
{
*min = ( int * )( a + i );
}
}
}
int main( void )
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
int *maxPtr = NULL;
int *minPtr = NULL;
MaxAndMin( a, N, &maxPtr, &minPtr );
printf( "The maximum value is %d at position %tu\n",
*maxPtr, maxPtr - a );
printf( "The minimum value is %d at position %tu\n",
*minPtr, minPtr - a );
}
The program output is
The maximum value is 9 at position 9
The minimum value is 0 at position 0
Pay attention to that the first parameter of the function should have the qualifier const because passed arrays to the function are not changed within the function.
The main issue is that the minnum is set at zero, which would only work if array had a negative value.
Setting minimum = star[0] also would not work!!! Because in the case of str[0] having negative value, *min never gets changed.
Also, I recommend to always initialize all variables in the declaration, especially pointers (because they may theoretically cause accidental access to memory).
Full solution:
#include <stdio.h>
int MaxAndMin(int* str, int** max, int** min)
{
int i;
int maxnum = 0;
int minnum = str[0] + 1;
for(i=0; i<5; i++)
{
if(maxnum < str[i])
{
maxnum = str[i];
*max = &str[i];
}
if(minnum > str[i])
{
minnum = str[i];
*min = &str[i];
}
}
return 0;
}
int main(void)
{
int i = 0;
int len = 0;
int* maxPtr = NULL;
int* minPtr = NULL;
int arr[5]={};
for(i=0; i<5; i++)
{
printf("Enter number %d: ",i+1);
scanf("%d", &arr[i]);
}
MaxAndMin(arr, &maxPtr, &minPtr);
printf("%d",*maxPtr);
printf("%d",*minPtr);
printf("Hi");
return 0;
}

empty pointers as an argument in C - problem with asterisks

The task is to fill an array with numbers by user input and then use our stats() function to calculate average etc. of each row of this array. The header of stats() function looks as follows:
int stats(int (*ptr)[5], int width, int height, int row_id, int* max, int* min, float *avg)
where ptr is a pointer to the matrix,width and height are its size, row_id is the index of analysed row and max, min and avg are pointers to variables storing each statistics.
When calling a function with such line:
stats(*ptr, 5,5,2, *max = NULL, *min = NULL, *avg=NULL);
the following error appears:
error: invalid type argument of unary '*' (have 'int')
I tried different approaches but there is always a mistake, how can I fix that? Thank you for any clues.
edit:
Here's the whole code:
#include <stdio.h>
int stats(int (*ptr)[5], int width, int height, int row_id, int* max, int* min, float *avg)
{
int j, vmax,vmin;
int max = &vmax;
int min = &vmin;
int i = row_id;
int m = *ptr;
for(j = 0; j<5; j++){
if(m[i][j]>max)
{
max = m[i][j] ;
j++;
else
j++;
}
}
printf("%d", max);
return 0;
}
int main(void){
int n, i, j, vmin, vmax; // vmax - value of the maximum
int min = &vmin; // min - pointer to the minimum
int max = &vmax;
float vavg;
int avg = &vavg;
int m[5][5];
for(i = 0; i<5; i++)
{
for(j = 0; j<5; j++)
{
printf("ENTER A NUMBER: ");
scanf("%d", &n);
m[i][j] = n;
}
}
int ptr = &m;
stats(*ptr, 5,5,2, *max = NULL, *min = NULL, *avg=NULL);
return 0;
}
Your code full of bugs.
For example min and max are not declared as pointers
int min = &vmin; // min - pointer to the minimum
int max = &vmax;
Also it is unclear why the variable avg has the type int and is initialized by a pointer expression of the type float *.
float vavg;
int avg = &vavg;
Or the variable ptr of the type int is initialized by the address of the two-dimensional array.
int ptr = &m;
As for the function then if the function operates only on one row then there is no any sense to pass to the function the whole two-dimensional array.
Also the return type and the returned value of the function do not make a sense.
And the function shall not output any message. It is the caller of the function that will decide output a message or not.
And also the function contains bugs where you are redeclaring its parameters like for example
int max = &vmax;
that again does not make a sense.
Using your approach the function can be declared and defined the following way
#include <assert.h>
//...
void stats( const int *a, size_t n, int *max, int *min, float *avg )
{
assert( n != 0 );
*max = a[0];
*min = a[0];
float sum = a[0];
for( size_t i = 1; i < n; i++ )
{
sum += a[i];
if ( *max < a[i] )
{
*max = a[i];
}
else if ( a[i] < *min )
{
*min = a[i];
}
}
*avg = sum / n;
}
And called like
int min = 0;
int max = 0;
float avg = 0.0f;;
//...
stats( m[2], 5, &max, &min, &avg );
printf( "max = %d\n", max );
printf( "min = %d\n", min );
printf( "average = %f\n", avg );
When you are using pointers as function parameters be carefull. If you have something like this:
int func(int *max){
}
max ,here, is a pointer which needs to hold an address. So inside this function when you need use it, you need to dereference it by using *. For example:
int func(int *max){
*max = $someAddress
}

Array sorting based on another array order

I am new to C and am having some issues with this code.
I need to split an array into two different arrays and sort the second array in whatever order the first one is.
Any thought please?
Below is where I got so far:
#include <stdio.h>
void main ()
{
int currentN;
int i, n;
int array[20];
printf("Enter the value of n\n");
scanf("%d", &n);
if (n%2 !=0)
{
printf("sequence would not be equ. please enter Odd \n");
printf("Please Enter even number\n");
scanf("%d", &n);
}
//add
printf("enter the numbers\n");
for (i = 0; i < n; ++i)
{
scanf("%d", &array[i]);
// scanf("%d", &currentN);
// seq[i]= currentN;
}
n++;
//add
int *firstHalf = malloc(n/2 * sizeof(int));
if (!firstHalf)
{
/* handle error */
}
int *secondHalf = malloc(n/2 * sizeof(int));
if (!secondHalf)
{
/* handle error */
}
memcpy(firstHalf, array, n/2 * sizeof(int));
memcpy(secondHalf, array + n/2, n/2 * sizeof(int));
for (i = 0; i < n/2; i++)
{
printf( "%d\t", firstHalf[i]);
//printf( "%d\n", secondHalf[i]);
//printf( "\n************************");
}
printf("\n*********************\n");
for (i = 0; i < n/2; i++)
{
printf( "%d\t", secondHalf[i]);
}
}
One way to get what you need:
Create a struct that has two members.
Create an array of the struct.
Fill the struct array such that the first half the original array are stored in the first member of the elements of struct array and the the second half of the original array are stored in the second member of the elements of the struct array.
Sort the struct array using the first member of the elements.
Just add this code after your last memcpy function:
int j, temp;
for(i = 0; i < n/2; i++)
{
for( j = 0; j < n/2 - 1; j++ )
{
if( firstHalf[j] > firstHalf[j+1] )
{
temp = firstHalf[j];
firstHalf[j] = firstHalf[j+1];
firstHalf[j+1] = temp;
temp = secondHalf[j];
secondHalf[j] = secondHalf[j+1];
secondHalf[j+1] = temp;
}
}
}
I have used basic bubble sort, but you can use any of the advanced sorting algorithms.
The trick, is that you just have to use the firstHalf array when doing the comparison, but when swapping, you swap elements in both the arrays.

How to declare two dimensional arrays using pointers?

Hello there I am having trouble declaring two dimensional arrays using pointers. I am new to C.
int main(){
int x = 0;
int y = 0;
int *xdim;
int *ydim;
printf("Enter x:\n");
scanf("%d", &x);
printf("Enter y:\n");
scanf("%d", &y);
xdim = &x;
ydim = &y;
char sq[xdim][ydim];
return 0;
}
I want the two dimentionial array char sq to hold the values inputed by the user. I get error non-integer type *int. I am also new to pointers.
Using VLAs (which are allowed in C99, or as an extension to many compilers), all you need to do is:
int xdim, ydim;
scanf("%d %d", &xdim, &ydim);
char vla_array[xdim][ydim];
As you can see, there is no need for pointers.
The 2nd option is to use "ordinary" arrays. You need to declare an array with big enough size, and use only a part of it:
#DEFINE X_MAX_DIM 100
#DEFINE Y_MAX_DIM 100
char vla_array[X_MAX_DIM][Y_MAX_DIM];
int xdim, ydim;
scanf("%d %d", &xdim, &ydim);
// check xdim and ydim are acceptable sizes
// from now on you use up to `xdim x ydim` of your array, even if
// it was declared as `100x100`
You can use this only when you know in advance the maximum allowed dimensions of your array.
The 3rd option is to use dynamic allocation. This is the only option if the array is very big. However this is an advanced topic, so you will not deal with this right now.
int** ptr = NULL;
ptr = new int*[val];
for(int i=0; i < val; i++)
{
ptr[i] = new int[val];
}
above code allocates 2d array of val*val
change char sq[xdim][ydim]; to char sq[*xdim][*ydim];, else you pass the location of the value rather than the value itself.
But it is unnecessary to use pointers in this case, you could just use x and y.
In the code you sowed the error occured because in this declaration
char sq[xdim][ydim];
there are used pointers xdim and ydim instead of integers. You could write
char sq[*xdim][*ydim];
Though there is no need to use pointers such a way.
If your compiler supports Variable Length Arrays then you can for example just write
int main( void )
{
size_t m = 0;
size_t n = 0;
printf("Enter x:\n");
scanf("%zu", &m);
printf("Enter y:\n");
scanf("%zu", &n);
if ( !m || !n ) return 1;
char sq[m][n];
//...
return 0;
}
Otherwise you have to allocate arrays dynamically. For example
#include <stdlib.h>
int main( void )
{
size_t m = 0;
size_t n = 0;
printf("Enter x:\n");
scanf("%zu", &m);
printf("Enter y:\n");
scanf("%zu", &n);
if ( !m || !n ) return 1;
char **sq = malloc( m * sizeof( char * ) );
for ( size_t i = 0; i < m; i++ ) sq[i] = malloc( n * sizeof( char ) );
//...
for ( size_t i = 0; i < m; i++ ) free( sq[i] );
free( sq );
return 0;
}
I believe if i understand what you're asking this should work.
Using a single pointer within a 2D array;
#include <stdio.h>
#include <stdlib.h>
int x = 0, y = 0;
char *arr = (char *)malloc(x * y * sizeof(int));

Segmentation Fault while allocating memory at run time using malloc [duplicate]

This question already has answers here:
How do I work with dynamic multi-dimensional arrays in C?
(9 answers)
Closed 8 years ago.
This is my code. My purpose is to allocate memory to a 2D array at run time upto whatever size is given in input.
Why is segmentation fault occuring? Is it because array elements have to be stored consecutively and malloc(dynamic allocation) is not letting this happen?
OR I am doing some error in writing this code. Please guide me through.
Thanks in advance.
int main(){
// STEP 1
int size,**arr,i=0,j=0;
printf("Enter the size of matrix : ");
scanf("%d",&size);
// STEP 2
arr = (int**)malloc(size*size*sizeof(int));
printf("\n Enter the %d elements : \n",size*size);
for(i=0;i<size;i++){
for(j=0;j<size;j++){
// STEP 3
scanf("%d",&arr[i][j]);
}
}
/*
for(i=0;i<size;i++){
for(j=0;j<size;j++){
printf("%d\n",matrix[i][j]);
}
}
*/
return 0;
}
This is a classic mistake.
A pointer to pointers is actually not the same as a two-dimensional array.
Granted, you can access elements of both via the var[x][y] syntax, but the memory layout of
int foo[x][y]
is different from
int **bar
If you really want to have this dynamic, you will have to allocate space for your list of pointers, then allocate space for your elements to each pointer in turn.
bar = malloc( x * sizeof(int*) );
for ( int i = 0 ; i < x ; i++ )
bar[i] = malloc( y * sizeof(int) );
If at all possible, you should try and avoid this in favor of an actual two-dimensional array, which as of C99 you can declare on the stack even if its size is determined at runtime:
int main()
{
int n;
scanf("%d", &n);
int array[n][n];
// ...
return 0;
}
You should allocate like this:
arr = malloc(size * sizeof(int*));
for (int i = 0; i <size; i++)
arr[i] = malloc(size * sizeof(int));
And do not forget to free the memeory using free.
Side Note: Do not cast the return value of malloc.
One idea that would work and would also get you rid of the memory fragmentation induced by this double pointers level allocation is make your matrix linear:
arr = (int*) malloc (size*size*sizeof(int));
And then simply access your elements with arr[i*size + j] instead of arr[i][j]:
use it like this : a perfect example of dynamic memory Allocation
void mxmult()
{
int n,m,a,b,c,d, sum=0;
int x,y,z;
printf("Enter first order [n*n]\n");
scanf("%d", &n);
printf("Enter second order [m*m]\n");
scanf("%d", &m);
if (n!=m)
{
printf("Invalid orders");
}
else
{
//mem allocate for matrix 1
int **mat1 = (int**)malloc(n*sizeof(int));
for(x=0;x<n;x++)
{
mat1[x]=(int*)malloc(n*sizeof(int));
}
// input matrix 1
printf("Enter the first matrix entries\n");
for (a = 0; a <n; a++)
{
for (b = 0; b < n; b++)
{
scanf("%d", &mat1[a][b]);
}
}
// memory allocate matrix 2
int **mat2 = (int**)malloc(m*sizeof(int));
for(y=0;y<n;y++)
{
mat2[y]=(int*)malloc(m*sizeof(int));
}
//inpur matrix 2
printf("Enter the second matrix entries\n");
for (c = 0; c <n; c++)
{
for (d= 0; d < n; d++)
{
scanf("%d", &mat2[c][d]);
}
}
//Memory allocate matrix Mult
int **mult=(int**)malloc(m*sizeof(int));
for(z=0;z<m;z++)
mult[z]=(int*)malloc(m*sizeof(int));
for (a = 0; a < n; a++)
{
for (d = 0; d < m; d++)
{
for (c = 0; c < n; c++)
{
sum=sum + (mat1[a][c] *mat2[c][d]);
}
mult[a][d] = sum;
sum= 0;
}
}
printf("Product\n");
for ( a = 0 ; a < n ; a++ )
{
for ( d = 0 ; d < m ; d++)
printf("%d\t", mult[a][d]);
printf("\n");
}
}
}

Resources