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);
Related
I'm writing this code in C for some offline games but when I run this code, it says "runtime failure #2" and "stack around the variable has corrupted". I searched the internet and saw some answers but I think there's nothing wrong with this.
#include <stdio.h>
int main(void) {
int a[16];
int player = 32;
for (int i = 0; i < sizeof(a); i++) {
if (player+1 == i) {
a[i] = 254;
}
else {
a[i] = 32;
}
}
printf("%d", a[15]);
return 0;
}
Your loop runs from 0 to sizeof(a), and sizeof(a) is the size in bytes of your array.
Each int is (typically) 4-bytes, and the total size of the array is 64-bytes. So variable i goes from 0 to 63.
But the valid indices of the array are only 0-15, because the array was declared [16].
The standard way to iterate over an array like this is:
#define count_of_array(x) (sizeof(x) / sizeof(*x))
for (int i = 0; i < count_of_array(a); i++) { ... }
The count_of_array macro calculates the number of elements in the array by taking the total size of the array, and dividing by the size of one element.
In your example, it would be (64 / 4) == 16.
sizeof(a) is not the size of a, but rather how many bytes a consumes.
a has 16 ints. The size of int depends on the implementation. A lot of C implementations make int has 4 bytes, but some implementations make int has 2 bytes. So sizeof(a) == 64 or sizeof(a) == 32. Either way, that's not what you want.
You define int a[16];, so the size of a is 16.
So, change your for loop into:
for (int i = 0; i < 16; i++)
You're indexing too far off the size of the array, trying to touch parts of memory that doesn't belong to your program. sizeof(a) returns 64 (depending on C implementation, actually), which is the total amount of bytes your int array is taking up.
There are good reasons for trying not to statically declare the number of iterations in a loop when iterating over an array.
For example, you might realloc memory (if you've declared the array using malloc) in order to grow or shrink the array, thus making it harder to keep track of the size of the array at any given point. Or maybe the size of the array depends on user input. Or something else altogether.
There's no good reason to avoid saying for (int i = 0; i < 16; i++) in this particular case, though. What I would do is declare const int foo = 16; and then use foo instead of any number, both in the array declaration and the for loop, so that if you ever need to change it, you only need to change it in one place. Else, if you really want to use sizeof() (maybe because one of the reasons above) you should divide the return value of sizeof(array) by the return value of sizeof(type of array). For example:
#include <stdio.h>
const int ARRAY_SIZE = 30;
int main(void)
{
int a[ARRAY_SIZE];
for(int i = 0; i < sizeof(a) / sizeof(int); i++)
a[i] = 100;
// I'd use for(int i = 0; i < ARRAY_SIZE; i++) though
}
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:
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've been tasked to code a program that processes a simple 1D array to return its element values, but the compiler has been behaving strangely; outputting more values than I have array elements.. It's also not being fully compliant with one of my statements (one that prints a new line character every 8 elements) and not assigning the largest value to my variable. I think that the other two problems will go away once the first problem is fixed, however.
Here is my brief:
Design, code and test a program that:
Fills a 20 element array (marks) with random numbers between 0 and 100.
Prints the numbers out 8 to a line
Prints out the biggest number, the smallest number and the average of the numbers
And here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int marks[20];
int i = 0;
int sum = 0;
int min;
int max;
for(i;i<=sizeof(marks);i ++){
marks[i] = rand() % 100;
sum += marks[i];
if(i % 8 == 0){
printf("\n");
}
printf("%d ", marks[i]);
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
}
printf("\n\nThe minimum value is: %d", min);
printf("\nThe maximum value is: %d", max);
printf("\n\nThe average value is: %d", sum / sizeof(marks));
return 0;
}
Please can someone help me get the correct output?
sizeof() function returns the byte length of the array, so this code "thinks" your array is 20 * whatever byte size ints are on your machine. You will want to just use i < 20 in the loop or go
for (i;i<sizeof(marks)/sizeof(int); i ++) { ...
Note that you probably do not want the <= operator in the for loop, since arrays are 0 indexed, thus marks[20] is actually one beyond the array.
There are two problem I can see that will invoke undefined behavior in your code.
By saying for(i;i<=sizeof(marks);i ++), you're out of bounds.
int min; int max; are not initialized and you're attempting to use it.
to solve this.
Change the for loop condition to for(i; i< 20; i++). Better to use a preprocessor construct like #define SIZ 20 and then make use of it accross your code to make it consistent and robust.
Initialize your local variables. max should be INT_MIN, and min can be INT_MAX. (see limits.h for reference).
To clarify more on point 2, max and min are automatic local variables, and in case not initialized explicitly, it contains indeterminate values.
C11, chapter §6.7.9,
If an object that has automatic storage duration is not initialized explicitly, its value is
indeterminate.
and then, directly from the Aneex J, §J.2, Undefined behaviour,
The value of an object with automatic storage duration is used while it is
indeterminate.
if(marks[i]>max){
max = marks[i];
}
else if(marks[i]<min){
min = marks[i];
}
min and max are not initialized here. Make sure to set your compiler warnings at the highest level, so you get a warning message when you forget to initialize variables.
for(i;i<=sizeof(marks);i ++){
This doesn't make sense. Replace sizeof(marks) with the number of times you want to loop, and use < instead of <=.
For example:
const int num_marks = 20; // or use #define
int marks[num_marks];
for(i = 0; i < num_marks; i++) {}
I am trying to get the size of my array but am having no luck...
I've read from various other threads that the way to grab the size of an array is:
theSize = (sizeof(array) / sizeof(array[0]))
But that seems to grab the empty elements of the array too.
How would we grab just the elements that are used up... for example:
char array[200][40];
for (i = 1; i < (sizeof(array) / sizeof(array[0])); i++) {
printf("%s", array[i-1]);
The output for an array that used 3 of its 200 elements would be...
First
Second
Third
(This is where it should stop, however it gives a bunch of question marks,
so I assume I'm grabbing memory i'm not supposed to use.
Note: I want it so that i < 3 for the loop (since the array has 3 elements used up)
There are two ways to do this.
The first way is to keep track of how many elements are used in a separate variable. Note that you must ensure that used is always less than of equal to the size of the array.
char array[200][40];
size_t used = 3;
for (int i = 0; i < used; ++i) {
printf("%s", array[i]);
}
The second way is to flag the first unused element with a special value, such as 0, and output all values until the flagged one. In your case, it would be natural to mark the end of the array with an empty string.
char array[200][40];
size_t size = sizeof(array) / sizeof(array[0]);
for (int i = 0; i < size && array[i][0] != 0; ++i) {
printf("%s", array[i]);
}