Program stops after loop in function - c

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.

Related

Segmentation Fault linear search algorithm

This algorithm is a linear search algorithm that finds the desired value. But when I compile this code, gives the segmentation fault in if(dizi[i]==aranan) this line. How can I solve this ?
#include <stdio.h>
int N,i,aranan;
int ArrayBastir(int *dizi,int N)
{
printf("My numbers\n");
for(int i =0; i<N;i++)
{
printf("%d\n", dizi[i]);
}
}
int findValue()
{
printf("The value you want to search");
scanf("%d",&aranan);
}
int Output(int *dizi,int N,int aranan)
{
for(int i =0; i<N;i++)
{
if(dizi[i]==aranan)
{
printf("%d number %d. found in queue \n", aranan,i+1);
}
}
}
int main() {
int N;
int aranan;
printf("Please enter how many numbers you want to enter");
scanf("%d", &N);
int dizi[N];
for(int i =0; i<N;i++)
{
scanf("%d", &dizi[i]);
}
ArrayBastir( dizi, N);
findValue(aranan);
Output(*dizi,N,aranan);
return 1;
}
Linear Search algorithm
You have two objects defined as:
int aranan;
Once is defined at file scope (a global), and one is defined within the scope of main.
When findValue(aranan) is called, a copy of the uninitialized value of aranan within the scope of main is passed to findValue. findValue is lacking a prototype, having not declared its arguments, so this is ignored.
findValue scans a value into the file scope aranan, but when Output(*dizi, N, aranan) is called it uses the value of aranan defined within main. aranan within main was never initialized, and thus this causes Output to search for an indeterminate value.
Additionally, *dizi is an int, when Output expects an int * as its first argument.
ArrayBastir and Output are also defined as each returning an int, which they do not do.
You should not ignore the return value of scanf, as it indicates the number of successful conversions, or a negative value on failure (EOF). In a program this small, you can get away with writing a simple wrapper function for reading integers, that just exits the program if the user enters something invalid.
main returning nonzero generally indicates your program failed. main is special - it is the only non-void function where you can omit a return statement. If main reaches the end of execution without an explicit return, it is treated as though it returned 0.
The issues above can be mitigated by avoiding the use of global variables, and by turning up your compilers warning level to catch obvious type mismatches.
For GCC or Clang, use -Wall -Wextra, and possibly -Werror.
For MSVC, use /Wall, and possibly /Wx.
Minimally refactored:
#include <stdio.h>
#include <stdlib.h>
int get_int(void)
{
int x;
if (1 != scanf("%d", &x)) {
fprintf(stderr, "Invalid input.\n");
exit(EXIT_FAILURE);
}
return x;
}
void ArrayBastir(int *dizi, int N)
{
printf("My numbers\n");
for (int i = 0; i < N; i++) {
printf("%d\n", dizi[i]);
}
}
void Output(int *dizi, int N, int aranan)
{
for (int i = 0; i < N; i++) {
if (dizi[i] == aranan) {
printf("Found <%d> at position %d.\n", aranan, i);
}
}
}
int main(void)
{
printf("Please enter how many numbers you want to enter: ");
int N = get_int();
int dizi[N];
for (int i = 0; i < N; i++) {
dizi[i] = get_int();
}
ArrayBastir(dizi, N);
printf("Enter the value you want to search for: ");
int aranan = get_int();
Output(dizi, N, aranan);
}

Segmentation fault when using malloc and realloc with arrays

I'm fairly new to c and I'm trying to understand and grasp malloc. My program takes an integer x input, then loops until x is met while also taking other integer inputs. I then do various calculations. However I'm getting a segmentation fault and I don't understand why.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void)
{
calculations();
}
void calculations()
{
int i;
int x;
int total = 0;
double squareRoot;
double overall;
scanf("%d", &x);
int* array = malloc(x * sizeof(int));
if (!array) {
printf("There isn't enough memory \n");
return;
}
int c = 0;
while (c < x) {
scanf("%d", &array[i]);
total = array[i] * array[i];
c++;
}
squareRoot = sqrt(total);
array = realloc(array, x * sizeof(int));
int b = 0;
while (b < x) {
overall = array[i] / squareRoot;
printf("%.3f ", overall);
b++;
}
}
The problem is with
scanf("%d", &array[i])
where, the value of i is indeterminate.
To elaborate, i is an uninitialized local variable and unless initialized explicitly, the contents remain indeterminate. Attempt to use that value, in this scenario, would lead to invokes undefined behavior.
Even if you initialize i, you never operated on i, so all the changes will be overwritten on a fixed index. You got to take care of this case, too.
Solution: Looking at the code, it appears, you may want to use
scanf("%d", &array[c]);
instead.

Scanf in to array

This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.

Creating a function for a random number 2D array

So, I have this code which I need to turn into a function:
int main(void) {
int i=0,seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
printf("\nSeed value is:%d\n\n",seed);
srand(seed);
int a[5][5];
int x,y;
printf("Matrix A:\n");
for(x=0;x<5;x++) {
for(y=0;y<5;y++) {
a[x][y] = rand() %51 + (-25);
printf("%d ",a[x][y]); }
printf("\n"); }
printf("\n\n");
So basically, it produces a 2D 5x5 array of random numbers. This works fine, however my next task is applying a function to this code, with the function name of:
void generate_matrices(int a[5][5])
I have tried multiple times, the closest I got to a successful code was:
#include <stdio.h>
#include <stdlib.h>
void generate_matrices(int a[5][5]);
int main(void) {
int a, seed;
printf("\n\nEnter seed integer value: ");
scanf("%d", &seed);
srand(seed);
printf("\nSeed value is:%d\n\n",seed);
generate_matrices(a);
return 0;
}
void generate_matrices(int a[5][5]) {
int y,z;
printf("Matrix A:\n");
for(y=0;y<5;y++) {
for(z=0;z<5;z++) {
a[y][z] = rand() %51 + (-25); }
printf("%d ",a[y][z]); }
printf("\n");
}
But this returns the error, "expected 'int(*)[5]' but arguement is of type 'int'.
All/any help is muchly appreciated. To be fair on my part, I have done 90% of the code. This is the only bit I need help with so that I can apply this to the rest of my code.
Cheers!
You have declared a as a single integer on this line int a, seed;
When you call the function with generate_matrices(a); you are passing a single integer instead of a pointer to an array.
Change your declaration line to int a[5][5], seed;
generate_matrices(a); will pass a pointer to the first element in your 5 * 5 array, to the function.
You should really print the results in main and not in the function, then you will know that the array has been modified and is available for use in the body of your program.
You have used unconventional placement of braces '}' and this makes it harder to see what belongs in each part of your for loops.
You have the print statements in the wrong places - as a result only part of the matrix is printed.
This is what it should be (just the results - in main):
printf("Matrix\n ");
for (y = 0; y < 5; y++) {
for (z = 0; z < 5; z++) {
printf("%d\t ", a[y][z]);
}
printf("\n");
}
If you use int a[5][5] and call the function with generate_matrices(a);
a function void generate_matrices(int a[5][5]) {...} compiles without error
#include<stdio.h>
#include<stdlib.h>
void modify(int b[5][5]);
int main()
{
srand(4562);
int i,j,arr[5][5];
modify(arr);
for(i=0;i<5;i++){
for(j=0;j<5;j++){
printf("%d ",arr[i][j]=rand() %51 + (-26)); }
}
return 0;
}
void modify(int b[5][5])
{
int i,j;
for(i=0;i<5;i++) {
for(j=0;j<5;j++) {
b[i][j]; }
}
}
So this is the closest I have come to completing it. It produces the number of elements I want, also within the range I want. However its not producing the 5x5 grid I need. Where have I gone wrong?
EDIT: I'm not going for neatness at the moment, I just want to get the program working how I want it too and then i'll neaten it up.
EDIT 2: Never mind, realised what I didn't include. Its fine now. Thanks for the help.

Changing the values in a number array in 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.

Resources