Problems with return value C - c

Getting problem with return (huge) value. I have already checked at the enthernet, but found nothing :( Hoping that here I could find answer to my question. I am just beginner, so hard to do something right if you dont know what is wrong ((
#include <stdio.h>
#include <math.h>
void MasivaIzveide (int *masivs, int x )
{
int i, reiz,n1,n2;
srand(time(NULL));
/* nosaka cik elementu masiva bus */
printf("Ievadi, divus masiva emelentus, kuri bus '0' starp kuram bus summa\n\n");
printf("\n Pirmais elements=");
scanf("%d", &n1);
printf("\n Otrais elements=");
scanf("%d", &n2);
for ( i = 0; i < x; i++ )
{
masivs[ i ] = rand() % 200-100 ; /* random vertibas katram masiva skaitlim*/
masivs[n1]= 0;
masivs[n2]=0;
printf("Loceklis[%d] = %d\n", i, masivs[i] );
}
return;
}
void Reizinajums (int *masivs, int x) {
int i, reiz;
reiz=masivs[2];
for (i=4; i < x; i=i+2) {
reiz=reiz*masivs[i] ;
}
printf("\n\nReizinajums ir %d\n\n\n\n ", reiz);
return;
}
void main(){
int i,j,s;
int masivs[i];
printf("Tiks izveidots masiivs\n\n\n\n");
MasivaIzveide(masivs,15);
Reizinajums(masivs,15);
return;
}
The problem is at the line (reiz=reiz*masivs[i] ;)
I am using pointers aswell.
Thanks for help.

This is a mistake:
int i,j,s;
int masivs[i];
You are declaring masivs with the dimension i but that is an uninitialized variable. That causes undefined behaviour. Perhaps you meant:
int masivs[15];
You should also check that n1 and n2 are in the correct range before using them as array indices.

Related

Changing the value of a variable with pointers not working

Basically I have a function called MinSubTab that is supposed to calculate the sum of the array passed and also to change the value passed in the first argument from inside the function without using return. This is done with pointers. Anyway, I think it'd be easier if I just showed you the code so here it is:
maintab.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tab.h"
int main(){
int *reftab;
int min;
reftab = (int *)malloc(sizeof(int) * NMAX);
InitTab(reftab,NMAX);
printf("\n Total: %d et min: %d", MinSumTab(&min, reftab, NMAX), min);
free(reftab);
return 0;
}
tab.c
void InitTab(int *tab, int size){
srand(time(NULL));
for (int i=0; i<size; i++){
*(tab+i) = rand() % 10;
}
}
int MinSumTab(int *min, int *tab, int size){
int total=0;
int minimum = NMAX;
int temp = *min;
for (int i=0; i<size; i++){
total += *(tab+i);
}
for (int i=0; i<size; i++){
if(*(tab+i)<minimum){
minimum = *(tab+i);
}
}
*min = minimum;
return total;
}
So the expected result here is that the sum is printed (which it is) and the minimum value of the array is printed (which it is not). Every single time the min variable equals 8 and I've no idea how to actually change the value of min from within that function.
Please help as my brain has no more capacity for rational thought, it's been 1.5 hrs and no solution in sight. Thanks
Looks like a small mistake:
You initialize minimum with NMAX, which I assume is 8 (the size of the array). 99.9% of the random numbers will be bigger. So 8 is chosen as the minimum.
What you really want is to initialize it with RAND_MAX – the maximum value rand() can return.
In C order of evaluation and argument passing is undefined.
You can of course the order yourself but it only to feed your curiosity.
#include <stdio.h>
volatile char *message[] = {
"fisrt", "second", "third", "fourth"
};
int print(size_t x)
{
printf("%s\n", message[x]);
return x;
}
int main()
{
printf("%d %d %d %d\n", print(0), print(1), print(2), print(3));
return 0;
}
Note. There is one exception from this rule.
Logical operators are evaluated form the left to the right.
if( x != NULL && *x == 5)is safe because x will not be dereferenced if it is NULL

program.exe (C) has stopped working

I am extremely new to C and managed to compile this program, but the exe stops working upon running. I'm really not sure what's wrong.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define TINY 1.0e-20 // A small number.
void ludcmp(float a[3][3], int n, int *indx, float *d);
void lubksb(float a[3][3], int n, int *indx, float b[]) ;
int main(){
int i,n,*indx;
float *b,d;
float a[3][3] = {
{ 1.0, 2.0, 5.0},
{-1.0, 2.0, 3.0},
{ 6.0, 0.0, 1.0}
};
ludcmp(a,n,indx,&d);
lubksb(a,n,indx,b);
for(i = 1; i = 3; i++) {
printf("%.2f",b[i]);
}
getchar();
return 0;
}
For those who were asking, the 2 functions ludcmp and lubksg are below. I got them from the numerical recipes textbook, but edited some lines to remove exclusive routines which I do not have. Specifically, they are the lines with malloc, printf, and free.
The original code came with all the loops starting with 1, which is why I also started my loop with 1. I have since changed all the loops to start from 0 instead, hopefully without introducing any new errors.
You can see the original code here:
https://github.com/saulwiggin/Numerical-Recipies-in-C/tree/master/Chapter2.Solution-of-Linear-Equations
Here is ludcmp:
void ludcmp(float a[3][3], int n, int *indx, float *d)
{
int i, imax, j, k;
float big, dum, sum, temp;
float *vv; // vv stores the implicit scaling of each row.
vv = (float *) malloc(n * sizeof(float));
*d=1.0;
for (i=0;i<n;i++) {
big=0.0;
for (j=0;j<n;j++)
if ((temp=fabs(a[i][j])) > big) big=temp;
if (big == 0.0)
{
printf("Singular matrix in routine ludcmp");
//free(vv);
}
// No nonzero largest element.
vv[i] = 1.0 / big; // Save the scaling.
}
// This is the loop over columns of Crout's method.
for (j=0;j<n;j++) {
for (i=0;i<j;i++) {
sum=a[i][j];
for (k=0;k<i;k++) sum -= a[i][k]*a[k][j];
a[i][j]=sum;
}
// Initialize for the search for largest pivot element.
big=0.0;
for (i=j;i<=n;i++) {
sum=a[i][j];
for (k=0;k<j;k++)
sum -= a[i][k]*a[k][j];
a[i][j]=sum;
if ( (dum=vv[i]*fabs(sum)) >= big) {
big=dum;
imax=i;
}
}
if (j != imax) {
for (k=0;k<n;k++) {
dum=a[imax][k];
a[imax][k]=a[j][k];
a[j][k]=dum;
}
*d = -(*d);
vv[imax]=vv[j];
}
indx[j]=imax;
if (a[j][j] == 0.0) a[j][j]=TINY;
if (j != n) {
dum=1.0/(a[j][j]);
for (i=j+1;i<n;i++) a[i][j] *= dum;
}
} // Go back for the next column in the reduction.
free(vv);
}
And lubksb:
void lubksb(float a[3][3],int n,int *indx,float b[])
{
int i,ii=0,ip,j;
float sum;
for (i=1;i<=n;i++) {
ip=indx[i];
sum=b[ip];
b[ip]=b[i];
if (ii)
for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j];
else if (sum) ii=i;
b[i]=sum;
}
for (i=n;i>=1;i--) {
sum=b[i];
for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j];
b[i]=sum/a[i][i];
}
}
This is a Two Dimensional Array and you are looping as it was just one. You should do something like:
for (int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
printf("%d %d: ", i+1, j+1);
}
}
Is bad practice to define the size of the array explicit. Try to use a constant.
And as said in the comments by #Marged:
In C arrays starts in 0
b is never assigned to anything valid when it's declared:
float *b,d;
At best, it's NULL or pointing to an invalid memory address:
I don't know what the lubksb function does:
lubksb(a,n,indx,b);
But b is clearly an invalid parameter since you never assign to it before calling this function.
And with this statement:
for(i = 1; i = 3; i++) {
printf("%.2f",b[i]);
}
As others have pointed out, array indices start at zero. But there's no evidence that b has a length of three anyway.

Find the highest number using another function

could everyone please help me what is wrong with my code or what is missing from my code...
We have this activity where we have to find the highest number using another function..
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int n1);
int main(int argc, char *argv[])
{
int i, num[10];
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num[i]));
getch();
}
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
When I input any number I always got 37..
int high (int n1); should be
int high (int *arr, int sz); /* You need to pass an array */
p("Highest Number: %d",high(num[i])); should be
p("Highest Number: %d",high(num, 10)); /* Passing array now, not one element */
int high() should be re-written as:
int high (int *arr, int sz)
{
int l, mx = INT_MIN;
for (l=0; l<sz; l++)
{
if (mx < arr[l])
{
/* Left as an excercise */
}
}
return mx;
}
As this is tagged c++, I would suggest using available C++ to find max in a range:
const int max = *std::max_element(&num[0], &num[10]); // #include <algorithm>
Well, I don't know if you still need an answer, but I corrected your code. Here are the mistakes I found
int high (int n1)
{
int l;
for (l=0; l<n1; l++)
{
if (n1 > l)
return n1;
}
}
In this for-loop, there is the condition l<n1 and inside the for loop you have the statement if(n1 > l) which will never be attained because of l<n1. You said you were getting 37 each time, but I was getting 10 instead. This shows it was undefined behavior because no real value was returned. ( This code part really didn't mean any sense either as this function doesn't even try to find the largest number ).
Another issue I found is you have used getch() without including <conio.h> ( Also pointing out that <conio.h> is not standard in C++ )
Well, even though this question is tagged C++, since the code is completely c, I have made a fixed code in c. I've removed getch() in the code. So here is the code
#include<limits.h>
#include <stdio.h>
#include <stdlib.h>
#define p printf
#define s scanf
int high (int *n1,int lar); // now I have used *n1 to get the address of the array.
int main(int argc, char *argv[])
{
int i, num[10],lar=INT_MIN; // the variable lar is given the minimum value that can be held by an int
p("Input 10 numbers\n");
for (i=0; i<10; i++)
{
p("Enter Number: ");
s("%d",&num[i]);
}
p("Highest Number: %d",high(num,lar)); // sending the entire array to the function by sending its address
}
int high (int *n1,int lar)
{
int l;
for (l=0; l<10; l++) // since the size you have taken for your array is 10, I have used 10 here. But if you don't know the size beforehand, pass the size as an argument to the function
{
if (n1[l] >lar ) // Well, this is the simple part
lar=n1[l]; // Simply assigning the largest value to lar
}
return lar; // Finally returning the value lar.
}
Well, hope this helps you.

accessing values in a struct array

I am passing in an array into a function straightflush. I use a counting loop so i can get to all of the elements but for some reason, even tho the counter i increases, i get the value and suit for the first element of the array. Therefore, only my spadesCount increases as it always shows 4 for the value and spade for the suit.
struct card{
int value;
char suit;
};
int straightflush(struct card hand[], int n)
{
int clubsCount = 0;
int diamondsCount = 0;
int heartCount = 0;
int spadesCount =0;
int i;
for(i=0; i<n; i++)
{
if (hand[i].suit == 'c')
{
clubsCount++;
}
else if (hand[i].suit == 'd')
{
diamondsCount++;
}
else if (hand[i].suit == 'h')
{
heartCount++;
}
else{
spadesCount++;
}
}
return 0;
}
here is my main:
int main(){
struct card hand1[] = {{4,'s'}, {9,'s'},{12,'c'},{11,'s'},{8,'s'},
{6,'d'}, {3,'d'},{7,'s'},{10,'s'},{12,'d'}};
printf ("%d\n", straightflush(hand1, 10));
}
I just run your code and the four count variables have correct values. I think it's because you are returning 0 at the end of your straightflush function, the output is always 0.
You can use a debugger or add the following line before the return statement in straightflush() to prove that your counts are actually accurate.
printf("%d %d %d %d\n", clubsCount, diamondsCount, heartCount, spadesCount);
Your return value has nothing to do with the values you read thus the printf statement in your main() function is not printing the count of any thing, it is just printing 0 no matter what.
If you want the counts accessible outside of striaghtflush() you need to either use global variables for those counts (a generally shunned idea) or pass some values in by reference. An example of this would be:
#include <stdio.h>
#include <stdlib.h>
void editValues( int *numDiamonds, int *numClubs, int *numHearts, int *numSpades ){
*numDiamonds = 3;
*numClubs = 5;
*numHearts = 7;
*numSpades = 11;
}
int main(int argc,char**argv)
{
int numD=0, numC=1, numH=2, numS=3;
printf("%d %d %d %d\n", numD, numC, numH, numS);
editValues(&numD, &numC, &numH, &numS);
printf("%d %d %d %d\n", numD, numC, numH, numS);
return 0;
}

factorial giving wrong answer

#include<stdio.h>
int max = 100;
int main()
{
int a,j;
int * arr = (int*)malloc(sizeof(int)*max);
arr[max-1] = 1;
scanf("%d",&a);
factor( arr, a);
display(arr);
}
int factor( int arr[],int a)
{
if (!a) return;
int i,carry;
for(i=max-1;i>=0;i--)
{
arr[i] = (arr[i]*a) + carry;
carry = arr[i]/10;
arr[i] = arr[i]%10;
}
factor( arr, a-1);
}
int display(int arr[])
{
int i;
for ( i=0; i<max; i++)
{
printf("%d",arr[i]);
}
}
HI this is my program to find the factorial of numbers but its giving wrong answer i dont know why ...???
like when i give input as 13
then according to myprogram 13 is to be treated in array as 1 and 3 but its giving random numbers -1216731443 -121673144 . i think malloc is having problem , but i can't identify it .
thank you
I think the reason why you are getting "random" numbers is because you haven't initialized the carry variable. In the for loop, you are adding the un-initialized value of carry to the array which will cause undefined results.

Resources