This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
random number in while loop [C programming] [duplicate]
(2 answers)
How can one print a size_t variable portably using the printf family?
(14 answers)
Closed 2 years ago.
I'm writing a program in C to add random numbers to an array. The size of the array is given (say n = 250) and using rand(), I'm generating these numbers (range is 1 to 100).
int main()
{
int n = 250;
int array[n];
for (int i = 0; i < n; i++)
{
srand(time(NULL));
int r = rand()%100 + 1;
array[i] = r;
}
printf("Output Size: %lu\n", sizeof(array));
return 0;
}
When I run the code, the result is-
Output Size: 1000
Expected result is 250. What am I doing wrong?
I think you're expecting n as output (number of elements in the array); but you're doing it wrong. Currently, what you're getting is 250*4 = 1000 (i.e., size of int is 4, and the number of elements is 250).
Replace sizeof(array) with sizeof(array)/sizeof (array[0])
Read this to dive deeper.
sizeof(type) returns the size, in bytes, of the type.
To find out size of array, you can do:
printf("Output Size: %zu\n", sizeof(array)/sizeof(array[0]);
Also, the type of the result of sizeof operator is size_t. You should use %zu format specifier instead of %lu.
You have 250 elements array, each array element is of size 4 bytes.
250*4 = 1000.
And you don't need to call srand in loop.
read this article about srand.
Related
This program worked fine when i manually iterated over 5 individual variables but when I substituted them for those arrays and for loop, I started getting floating point exceptions. I have tried debugging but i can't find were the error comes out from.
#include <stdio.h>
int main(void) {
long int secIns;
int multiplicadors[4] = {60, 60, 24, 7};
int variables[5];
int i;
printf("insereix un aquantitat entera de segons: \n");
scanf("%ld", &secIns);
variables[0] = secIns;
for (i = 1; i < sizeof variables; i++) {
variables[i] = variables[i - 1]/multiplicadors[i - 1];
variables[i - 1] -= variables[i]*multiplicadors[i - 1];
}
printf("\n%ld segons són %d setmanes %d dies %d hores %d minuts %d segons\n", secIns, variables[4], variables[3], variables[2], variables[1], variables[0]);
return 0;
}
The problem is you're iterating past the ends of your arrays. The reason is that your sizeof expression isn't what you want. sizeof returns the size in bytes, not the number of elements.
To fix it, change the loop to:
for (i = 1; i < sizeof(variables)/sizeof(*variables); i++) {
On an unrelated note, you might consider changing secIns from long int to int, since it's being assigned to an element of an int array, so the added precision isn't really helping.
Consider this line of code:
for (i = 1; i < sizeof variables; i++) {
sizeof isn't doing what you think it's doing. You've declared an array of 5 ints. In this case, ints are 32-bit, which means they each use 4 bytes of memory. If you print the output of sizeof variables you'll get 20 because 4 * 5 = 20.
You'd need to divide the sizeof variables by the size of its first element.
As mentioned before, sizeOf returns the size of bytes the array holds.
Unlike java's .length that returns the actual length of the array. Takes a little bit more of knowledge with bytes when it comes to C.
https://www.geeksforgeeks.org/data-types-in-c/
This link tells you a bit more about data types and the memory(bytes) they take up.
You could also do sizeOf yourArrayName/sizeOf (int). sizeOf(datatype) returns the size of bytes the data type takes up.
sizeof will give the size (in bytes) of the variables and will yield different results depending on the data type.
Try:
for (i = 1; i < 5; i++) {
...
}
This question already has answers here:
random element from array in c
(5 answers)
Closed 2 years ago.
Basically i made an array with number 1,2,3.
int array[3] = {1,2,3};
How can I select a random number from this list and assign it to a different variable?
Use the rand() function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:
srand(time(NULL));// without this rand() function might continuously give the same value
int index = rand() % 3;
printf("random: %d\n", array[index]);
Considering that the array contains hardcoded values, you could simply:
int i = (rand() % 3) + 1;
printf("random: %d\m", i);
Include the header file <stdio.h>, <time.h>, <stdlib.h>
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);
This question already has an answer here:
Why the size of pointer to array is always 8 in C? [duplicate]
(1 answer)
Closed 3 years ago.
I'm making a program capable to use some statistics functions. For that, I used malloc for the array that the numbers of the sample to operate on, as I want it's size to be based on users' input. It's not the first time I do this, and it worked fine, but this time I can't set the size as needed and I can't find the flaw.
Below is the necessary code for the creation and printing of the array, skipping main() as it only runs the functions.
int *sample;
int MakeSample()
{
int sampleSize;
int valueN;
printf("Enter size of your sample: ");
scanf("%d", &sampleSize);
sample = malloc(sampleSize * sizeof(int));
for (int i = 1; i <= sampleSize; i++)
{
printf("Enter value #%d: ", i);
scanf("%d", &valueN);
sample[i - 1] = valueN;
}
}
int PrintSample()
{
for (int k = 1; k <= sizeof(sample); k++)
{
printf("Value #%d: %d\n", k, sample[k - 1]);
}
}
If I enter size 1 for the array, that should be the amount off values asked for and printed, instead I got this:
Value #1: 1
Value #2: 0
Value #3: 0
Value #4: 0
Value #5: 0
Value #6: 0
Value #7: 133057
Value #8: 0
sample is an int pointer; sizeof(sample) is always 8. You need to store the sampleSize variable somewhere and use that instead - there's no way for your program to know how big your array is otherwise, since it's not really an "array", it's a pointer to memory that happens to hold an array.
This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
Closed 8 years ago.
I am trying to use a for loop to assign values to an array in C (I'm using minGW). At first I tried doing:
double flag[5] = {0.1};
but that only assigned the first variable in the array to 0.1. Then I tried doing a for loop to assign each individually. The reason why I don't want to hard code it is because I want the size of the flag variable to be flexible to the user's input. My current code looks like this:
int cnt;
double flag[5];
for (cnt = 0; cnt < sizeof(flag); cnt++) {
printf("sizeof(flag) is %d\n",sizeof(flag));
printf("size is equal to %d and cnt is %d\n",size,cnt);
flag[cnt] = 0.1;
}
printf("size is equal to %d\n",size);
The variable "size" changes from 6 as it was previously determined to a garbage number, and I cannot modify the number of iterations. For example, if I set cnt < sizeof(flag)-1, there is no change. -2,-5, etc no change. However if I drastically reduce the size, it gets stuck in an infinite loop. sizeof(flag) is 40, not 5 like I'd want it to be, but dividing by 8 also gets it into an infinite loop somehow. Any advice?
This question was answered, thank you everyone!
The number of elements of flag array is not:
sizeof (flag)
but
sizeof flag / sizeof *flag
The former is the size in bytes of the array, the latter is the size in bytes of the array divided by the size in bytes of one element of the array.
change :
for (cnt = 0; cnt < sizeof(flag); cnt++)
to
for (cnt = 0; cnt < sizeof(flag)/sizeof(double); cnt++)
use
for (cnt = 0; cnt < sizeof flag / sizeof *flag; cnt++)
{
}
sizeof() returns # of bytes required for that variable which is 5*sizeof(double). So your loop is running for more than 5 times causing overflow.
Apart from the solutions suggested in earlier answers, you can have a macro for size of the array and use this macro and run loop till that value.
#define SIZE 5
.
.
.
int cnt;
double flag[SIZE];
for (cnt = 0; cnt < SIZE; cnt++) {
printf("sizeof(flag) is %d\n",sizeof(flag));
printf("size is equal to %d and cnt is %d\n",size,cnt);
flag[cnt] = 0.1;
}
printf("size is equal to %d\n",size);