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.
Related
I just have a function that finds out the maximum value of an array of integers, but I get a segmentation fault, which I can't find because the compiler doesn't show me the line of the error.
This is my C code:
#include <stdlib.h>
#include <stdio.h>
//Funktion ermittelt den größten Wert eines Arrays
int groesstesElement(int **arrayPointer){
int max = 0;
for (int i = 0; i < 3; i++) {
if (*arrayPointer[i]>max) {
max = *arrayPointer[i];
}
}
return max;
}
int main (int argc, char **argv) {
int array[4]={1,2,3,4};
int *ptr = array;
int z = groesstesElement(&ptr);
printf("%d\n", z);
return EXIT_SUCCESS;
}
I use macOS and VSC.
In C, array indexing [] has higher precedence than pointer de-referencing *: https://en.cppreference.com/w/c/language/operator_precedence
Some parentheses fix the segfault.
if ((*arrayPointer)[i]>max) {
max = (*arrayPointer)[i];
}
Due to the operators precedence, with
*arrayPointer[i]
you are telling your program:
Take the i-th element of the array arrayPointer and dereference it.
But arrayPointer is a pointer to int *, so all you get is the address of ptr (the int ** pointer defined from main) with an offset. When you finally dereference it you are likely accessing an invalid address, causing segmentation fault.
As already suggested by the main answer, the fix is done using parenthesis in order to apply the operators in the order you want:
(*arrayPointer)[i]
Secondary issues in the code
Even though with the correction above the program won't crash anymore, it won't work. Searching through the array with the loop
for (i = 0; i < 3; i++)
you won't include the last item in the search (index 3), skipping precisely the index that, in your example, contains the maximum value. You probably meant for (i = 0; i < 4; i++) or for (i = 0; i <= 3; i++).
Anyway, using magic numbers in the code (in this case the dimension of the array) is considered bad practice. A better solution would have been using a #define, but an even better solution would have been passing to the function the size of the array:
#include <stdlib.h>
#include <stdio.h>
#define ARR_SIZE 4
//Funktion ermittelt den größten Wert eines Arrays
int groesstesElement(int *arrayPointer, unsigned int arrSize){
int max = 0, i;
for (i = 0; i < arrSize; i++) {
if (arrayPointer[i]>max) {
max = arrayPointer[i];
}
}
return max;
}
int main (int argc, char **argv) {
int array[ARR_SIZE]={1,2,3,4};
int z = groesstesElement(array, ARR_SIZE);
printf("%d\n", z);
return EXIT_SUCCESS;
}
Please note how there's no need to use a double pointer anymore.
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
/this code is for rotating the array with n no of entries k no of times
and outputting the array elements at indexz q no of times/ my problem here is that it is showing runtime error why is it happening like that.this question is actually from hacker rank and it is by the name of circular array rotation in implimentation section in algorithms.is there anything wrong in this code.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n,k,q;
int a[n];
scanf("%d%d%d",&n,&k,&q);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
for(int j=0;j<k;j++)/*this is for rotating the array*/
{
int y=a[n-1];
for(int x=n-2;x>=0;x--)
a[x+1]=a[x];
a[0]=y;
}
for(int b=0;b<q;b++)
{
int z;
scanf("%d",&z);
printf("%d\n",a[z]);
}
return 0;
}
Problem:
int n,k,q;
int a[n];
You are creating an array of size n before setting the value of n.
Use:
int n,k,q;
// Read a value into n first
if ( scanf("%d%d%d",&n,&k,&q) != 3 )
{
// Deal with error
return 1;
}
// Then define the array.
int a[n];
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.
im a 1st grader when it comes to c and need help with storing 5 random values in an array and outputting them. Heres where am at.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
struct score_card {int A_ones; int B_twos; int C_threes; int D_fours; int E_fives; int F_sixes; int G_chance;};
int dice_rolls[5];
int randomize(void);
int value;
int main(void) {
struct score_card test;
randomize;
int i;
for(i = 0; i <= 4; i++){
printf("%d\n", dice_rolls[i]);
}
printf("\n");
return 0;
}
int randomize(void){
int i;
srand(time(0));
for(i = 0; i <= 4; i++){
value = rand() % 6 + 1;
dice_rolls[i] = value;
}
}
The output is :
6294304
6294308
6294312
6294316
6294320
the goal was to use modular division to get values from 1 -->6 and store them in the dicerolls array.
I see two immediate problems.
First. you're not terminating your random numbers with a newline. That's why they're all strung together in a big sequence. Change your output line to:
printf("%d\n", &dice_rolls[i]);
Secondly, you're not actually calling randomize. The correct way to call it is with:
randomize();
The statement randomize; is simply an expression giving you the address of the function. It's as useless in this case as the expression 42; which also does nothing. However it's valid C so the compiler doesn't necessarily complain.