Changing the values in a number array in C - c

I want to make a program that uses a function I created where it swaps all the elements of an array X (that has the length of N) with some number K, only if that element is greater than K. Where am I going wrong here?
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K);
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("%d",X[i]);
}
}
int swap_K(int *X, int K)
{
int i;
for (i=1; i<=sizeof(X)/sizeof(int); i++){
if (X[i]>K)
X[i]=K;
}
return X;
}

In swap_K(int *X, int K), sizeof(X) is sizeof(int *), not the size of the array.
In C, a pointer is not really the same as an array.
To fix it, use N instead of sizeof(X)/sizeof(int) everywhere, esp. inside swap_K().

1) Arrays start with index 0.
2) In your main function you don't need to use sizeof(X)/sizeof(int) in for loop as you already know it is equal to N.
3) When you pass the array to the function, you are sending the base address of the array which decays into pointer, so in swap_K function, sizeof(X) will return sizeof(int) which is 4(generally).
To overcome this you should send the size of your array from main function. For example: swap_K(X,K,N);
4) You don't need to return X from swap_K as you are sending the base address of X from main function.
For example:
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=0; i<N; i++)
{
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K,N);
for (i=0; i<N; i++)
{
printf("%d",X[i]);
}
}
int swap_K(int *X, int K,int N)
{
int i;
for (i=0; i<N; i++)
{
if (X[i]>K)
X[i]=K;
}
//return X; //This is not required
}

Your loop is incorrect
for (i=1; i<=sizeof(X)/sizeof(int); i++)
It should be
for (i=0; i<N; i++)

There are several problems with the code posted:
arrays in C are 0-indexed, so the for loops should ALWAYS iterate from 0 to N - 1. Iterating past N is a buffer overflow
the pointer to the array is just the pointer to the first element of the array. The swap function can't know if the pointer passed to it is part of an array or a single value. With this in mind it will need to take another argument which tells what is the size of the passed in array as pointer. Iteration inside the loop will use that value instead of sizeof(X) / sizeof(int) = 1
you're defining X as a variable sized array which is allocated entirely on the stack. Introducing a reasonably large N will crash your program. It would be better to allocate the array in the heap if you don't know what the size of the input will be.

Related

Read a list of n numbers and make an array in C

So I want to take an input such as this:
The first input tells us the size of the array and the second line contains the numbers of array like this:
input:
3
1 2 3
And I want to make an array from the second input line with a size of from the first input line.
I currently have:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n;
scanf("%d", n);
int x[n];
int y[n];
}
But after which I get stumped.
If you have a VLA(Variable Length Array) supporting compiler(eg. GCC):
int n;
scanf("%d", &n);
int arr[n];
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
and if not,
int n;
scanf("%d", &n);
int *arr = malloc(n * sizeof(int));
scanf("%d %d %d", &arr[0], &arr[1], &arr[2]);
This code uses the functionality of scanf to be able to take multiple delimited input.
If you have to take n inputs and not only set the size of arr to n, do this:
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &n[i]);
}
It should be apparent that VLA functionality lets you to make an array on the stack with a runtime value. Otherwise, you'll need to allocate it on the heap with malloc().
What if there are more than 3 numbers to scan. Do I need to add more
"%d" and arr[] or is there some way for it to work with any number of
numbers in the second line.
To address this point you can go with iterating over loop
for(int i=0;i<n;i++)
{
scanf("%d",&array[i]);
}

Problem in C : How to properly call function inside main

So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];

Program stops after loop in function

My prog doesn't reach outArray function. it stops after loop of fillArray function. Why this happens. It looks strangely, cause it's simple void function and shouldn't return anything. This should continue run commands in main. And that stops as usual program without any problems and bugs
#include <stdio.h>
#define N 100
int enterNofArray();
void fillArray(int n, float arr[N]);
void outArray(int n, float arr[N]);
int main()
{
float arr[N], sum = 0.0, average;
int n;
//input
n = enterNofArray();
//compute
fillArray(n, &arr[N]);
//output
outArray(n, &arr[N]);
return 0;
}
int enterNofArray()
{
int n;
printf("Enter amount of array...\n");
scanf("%d", &n);
while (n < 1 || n > N)
{
printf("Incorrect!!\n");
printf("Enter in range 1 - 100...\n");
scanf("%d", &n);
}
return n;
}
void fillArray(int n, float arr[N])
{
int num;
for(int i = 0; i < n; i++)
{
printf("Enter number for array[%d times left]...\n", n - i);
scanf("%d", &num);
arr[i] = num;
}
}
void outArray(int n, float arr[N])
{
for(int i = 0; i < n; i++)
{
printf("%f ", arr[i]);
}
}
&arr[N] refers to the memory location (or lvalue) that contains the N-th (out of index!!!) element in the array.
That code invokes Undefined Behavior (UB).
So, you weren't actually passing the whole array to your functions, you were just attempting to pass the N-th element of that array... Read more about that expression here.
Change this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
to this:
fillArray(n, arr);
outArray(n, arr);
Live Demo
The problem was that with your code n was corrupted, containing garbage value after the call to fillArray function. As a result, when outArray function was called, n had a garbage value, which resulted in an uncontrolled for-loop that ended in looping far further than the limits of your array, eventually accessing memory that you didn't own, thus causing a Segmentation Fault.
Not the cause of your problem, but I suggest you do scanf("%f", &num); in your fillArray function (after declaring num as a float of course), since you want to populate an array of floats.
Because you're send double pointer when you do this:
fillArray(n, &arr[N]);
outArray(n, &arr[N]);
Looks like:
fillArray(n, **arr);
outArray(n, **arr);
This happends so much when you work with Structures.

Program crash while trying to print a bidimensional array

as the title says, my program crashes when i try to print a bidimensional array.
The error is surely printf in function printarray, but i couldn't understand why it lead to crash.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array[n][m],n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
If an array dimension has size N then the valid range of indices is [0, N - 1].
So the loops in the function should look like
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i< col;i++){
//printf("lol3 %d",i);
for( j=0; j<row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
The same is valid for loops in main.
This call of the function invalid
printarray(array[n][m],n,m);
There shall be
printarray(array,n,m);
Take into account that such a declaration of an array like
int array[COL][ROW];
is very confusing. It would be more correctly to write
int array[ROW][COL];
^^^ ^^^
Also it is not clear what is the meaning of variables p and q in this loop
does not make sense
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
It seems that this loop is from some other program.:)
And you have to check that n and m are not greater than ROW and COL.
Also it is a bad idea to mix l'Italian with English.:)
The posted code does not cleanly compile, for several reasons.
1) missing
#include <time.h>
2) function main() ALWAYS returns 'int' so a proper main statement would be: 'int main( void )'
3) the first parameter to 'printarray()' is defined to be a pointer to a 2 dimensional array.
However,
a) the actual call passes the contents of a specific 'cell' in the array.
b) the passed 'cell' is beyond the end of the array.
Suggest: 'printarray( array, n, m )' as the calling statement.
Note, in C, an array name degrades to the address of the first entry in the array.
4) an array should be defined as arrayName[numRows][numColumns].
This will become much more important when declaring an array of pointers where each pointer will point to the contents of the associated row.
In the posted code, the definition/naming is backwards from typical.
in Memory, an array is laid out left to right (the columns) then top to bottom (the rows).
The 'biggest' index is rows and should be listed first.
5) to avoid text replacement problems, numeric values in macros should be wrapped in parens.
6) as a suggestion, appropriate vertical spacing (blank line) between code blocks makes the code much clearer and more understandable by us humans
7) when calling scanf() (and family of functions) always check the returned value (not the parameter values) to assure the operation was successful
8) consistent indentation makes the code much easier to read/understand by us humans, suggest: indent 4 spaces after every opening brace '{' and un-indent before every closing brace '}'. Note: Never use tabs for indenting. Different environments have different tab widths and/or different tab stops.
9) for readability, and to make debug much easier, only place one statement per line of code. This applies to declaring variables, so they can be easily commented and applies to executable statements
here i am attaching the your program without any error. the problem was to calling the printarray function.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array,n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}

Can anybody resolve my mistake

I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()

Resources