Calculating the minimum element in an array [duplicate] - c

This question already has answers here:
Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]
(6 answers)
Closed 7 years ago.
I've written a little program to determine the minimum element in an array a[]. When I debug, the program seems to be working fine initially but then the for loop in the min() function stops execution after two steps, despite the array being of size 10.
The final output is 23, when it sould be 3.
Is the code sizeof(a)/sizeof(int) incorrect? I found it on another article on stackoverflow.
#include <stdio.h>
#include <limits.h>
int min(int[]);
int main(){
int a[]={100,23,3,4,5,6,7,8,9,10};
printf("%d", min(a));
return 0;
}
int min(int a[]){
int min = INT_MAX, i;
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++){
if((i>=0) && (a[i]< min))
min = a[i];
}
return min;
}

Inside the function, a is a pointer to integer array, so sizeof(a) returns the size of a pointer which is typically 4 or 8 bytes depending on the system. Saying that, it is not possible to count the number of elements in a C array using sizeof(a)/sizeof(a[0]) inside the function. You need to pass the number of elements explicitly as an argument to the function.
int min(int a[], int n) {
...
for (i = 0; i < n; i++) {...}
...
}
printf("%d", min(a, sizeof(a)/sizeof(a[0])));

Related

C - passing array in function an get its size [duplicate]

This question already has answers here:
Find the Size of integer array received as an argument to a function in c [duplicate]
(4 answers)
Closed 2 years ago.
I am a Python user for quite a time now and now try to get into C. While Python does a lot in background for me i now have to code in C in a much more 'BASIC' way. I like it,... but its hard.
The important part starts here
I really like the len() method in Python to get the length of an array. But in C it seems as if i have to look for the size (in bytes) of an array and divide it by the size (in bytes) of one element to get the length for the hole array.
If there is a simple or a more common way i would like to here about it. However i want to understand why the following program prints me different sizes for my array 'a'.
#include <stdio.h>
void print_array(int a[]){
printf("size of 'a' in the function is: %d\n", sizeof(a));
}
int main(void){
int a[5] = {0, 2, 4, 8, 16};
printf("size of 'a' before the function is: %d\n", sizeof(a));
print_array(a);
return 0;
}
The output is the following:
size of 'a' befor the function is: 20
size of 'a' in the function is: 8
At least i want to write a function that prints and array which i donĀ“t know the length of. What how i understand, in C is only possible by looping truth it. This is the code i would add to the 'print_array' function. But it does it not how i aspected it to do because of the 'wrong' size.
int loop = sizeof(a)/sizeof(a[0]);
for(int i = 0; i <= loop; i++){
printf("Array[%d] = %d\n", i, a[i]);
}
Output (element 3 and 4 are missing):
Array[0] = 0
Array[1] = 2
Array[2] = 4
Thanks a lot for any explanation!
In C you must pass in not only the array, which decays to a pointer, but the size of the array as well. In C the common convention is (array, size):
void print_array(int a[], size_t s) {
for (size_t i = 0; i < s; ++i) {
... a[i] ...
}
}
Where you call it like:
print_array(a, 5);

Why using asterisk when using size in C language?

So the question is originated from Leetcode:
In a n * m two-dimensional array, each row is sorted in increasing order from left to right, and each column is sorted in increasing order from top to bottom. Please complete a function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.
And my C solution is:
1 bool findNumberIn2DArray(int** matrix, int matrixSize, int* matrixColSize, int target){
2 //return matrixSize==5;
3 for(int i = 0; i < matrixSize; i++)
4 {
5 for (int j = 0; j < *matrixColSize; j++)
6 {
7 int num = matrix[i][j];
8 if (num == target) {return true;}
9 if (num > target) {break;}
10 }
11 }
12 return false;
13}
In row 5, It has to be *matrixColSize. If I remove the asterisk, the memory will overflow. From my perspective, the matrixColSize is an INT. Why can't I use the INT directly but have to use a pointer?
Maybe I didn't make my question clear. I know it's a pointer, and I know a pointer is totally different from an INT. My question is, why is this question using a pointer here to define the matrixColSize but not just using and INT? From my perspective, an INT is enough here to represent the size.
Can anybody tell me why please?
Because you define as a function parameter int* matrixColSize if you delete * in 5. line, you basically say that increase j till address of matrixColSize.
And it is very large number because an address like 0x88644278. So thats why I guess your memory overflows. If you want to just int you must change your function parameters to bool findNumberIn2DArray(int** matrix, int matrixSize, int matrixColSize, int target) and in 5. line you can write without an asterisk.

Write a program that will create an integer array with 1000 entries

Write a program that will create an integer array with 1000 entries. After creating the array, initialize all of the values in the array to 0. Next, using the rand function, loop through the array and save a random number between 1 and 10 (inclusive) in each entry of the array.
This is for my homework due tomorrow but I need some help with it since I'm barely a beginner at code.
This is the only code I've made so far with single dimensional arrays
#include <stdio.h>
#include <stdlib.h>
int mean(int array[], int size);
int main()
{
int i;
int array[5]={5, 1, 3, 2, 4};
for (i=0; i<5; i++)
{
printf("%d", array[i]);
}
printf("\nThe mean is %d", mean(array,5));
return 0;
}
int mean(int array[], int size)
{
int i, sum = 0;
for (i=0; i<5; i++)
{
sum=sum + array[i];
}
return sum/5;
}
Not sure why you wrote a program to calculate the mean, given that there's nothing in the requirements about that.
However, you just have to think about the steps. Note that the following example do not perfectly match what you need, they're there just to show you the method, not to be cut and pasted into your assignment.
First, you can create an array of size (for example) seven with the statement:
int value[7];
You can then set all elements to a given value with:
for (size_t idx = 0; idx < sizeof(value) / sizeof(*value); idx++)
value[idx] = 42;
(although, at the level of your assignment, it's probably better to use 7 rather than the sizeof expression).
In order to generate random numbers, you first include the requisite header and, as the first thing in main(), set the seed to something "random":
#include <stdlib.h>
#include <time.h>
:
srand (time (0));
Then, at the time when you need to generate a random number from one to fifty inclusive, you can use:
int rnum = rand() % 50 + 1;
(keeping in mind the distribution won't be perfect but it should be more than good enough for the intended purpose here).
Whatever loop you chose above to initialise the array elements to 42 (or zero) can also be used to set them to random values.
That should be enough to get you started.

Function returning pointer called twice from main() [duplicate]

This question already has an answer here:
srand function is returning same values
(1 answer)
Closed 8 years ago.
I'm trying to make a function that generates random matrixes.
I'm not great at pointers but i really thought this should work.
Here's my function that I call twice from main, and that generates the same matrix in both cases...
int **generate_matrix(size_t m, size_t n){
int i1,i2;
int **ptr1=(int **)malloc(sizeof(int *)*m);
srand(time(0));
for(i1=0; i1<m; i1++){
ptr1[i1] = (int*)malloc(sizeof(int)*n);
for(i2=0; i2 < n; i2++){
ptr1[i1][i2]=rand()%10;
}
}
return ptr1;
}
In main i call them in a normal way:
int **matrix1,**matrix2;
matrix1=generate_matrix(3,3);
matrix2=generate_matrix(3,3);
(...)
//prints and stuff
free(matrix1);
free(matrix2);
You are seeding your rand with srand(time(0));. If your calculations are fast enough (i.e. the next second is not reached) time will return the same value twice due to its granularity of 1s.
You could check your results by seeding with definitely different numbers.

How to make random value function return different value each time [duplicate]

This question already has answers here:
Same random numbers every loop iteration
(4 answers)
Closed 8 years ago.
I've been trying to write a small C function for generating random values. The problem is that it returns same value each time the function is called in for loop. I understand the problem is that srand is seeded with NULL. What I want to know is how to correct it, so that on each iteration of for loop the function returns a different value. Here's the code:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int,int);
void main(){
int min=100, max=200,i=0;
for(i;i<11;i++){ printf("%d \n",randInt(min,max)); }
}
int randInt(int a,int b){
srand(time(NULL));
int randValue;
randValue=1+(int)rand()%(b-a+1);
return randValue;
}
Please let me know if you have a solution or can post some reference to a solution. Thank you in advance !
Edit : Encountered Problem #2, after having replaced srand(time(NULL)) into main, every iteration now generates numbers bellow my range, i.e. originally i wanted numbers between 100 and 200, but it also included numbers between 0 and 100. This was solved with randValue=a+(int)rand()%(b-a+1); as suggested in the comments
Put srand(time(NULL)); in main just after the {
To generate random numbers in the range 100-200,instead of adding 1,add 100 or a to
randValue=(int)rand()%(b-a+1);
So that it looks like:
randValue=(int)rand()%(b-a+1)+100;
This will print random value each time between 100-200:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int randInt(int a,int b)
{
int randValue;
randValue = (rand() % (b-a+1)) + a;
return randValue;
}
int main(void) {
int r=0, i = 0;
srand(time(NULL));
do
{
r = randInt(100,200);
printf("%d\n",r);
i++;
}while(i < 11);
puts("Done!");
return 0;
}
I am using min and max insead of a and b. It is better for future readers of your code
You should use srand(time(NULL)) only once at initialization e.g in your main()
You probably wanted min + rand() % (max - min + 1) instead of rand()%(b-a+1)

Resources