Weird behavior when printing array in C? - c

I am trying to print an array however I am not getting the desired output, weird numbers appear after the loop finishes printing the pre-defined array.
Code is:
#include <stdio.h>
int main(){
int intArray[11] = {1,2,8,12,-13,-15,20,99,32767,10,31};
int i=0;
for(i=0;i<sizeof(intArray);i++){
printf("%d\n",intArray[i]);
}
}
Output:
1
2
8
12
-13
-15
20
99
32767
10
31
11
1629976468
2674040
2665720
1627423265
1
2665616
-2147417856
1629976534
1629976468
2674040
0
1627423172
1629976532
0
1629110043
0
0
0
0
0
0
0
0
0
0
0
1629976538
0
1629956432
2674276
0
1627407935

The breaking condition in for loop is wrong! Which causes an index-out-of bound problem as i exceeds the maximum index value that is 10 because array length is just 11. The loop break condition should be < length of array( =11) but not < size of array.
Value of sizeof(intArray) is equals to 11 * sizeof(int) (= 44).
To understand it read: sizeof Operator:
6.5.3.4 The sizeof operator, 1125:
When you apply the sizeof operator to an array type, the result is the total number of bytes in the array.
According to this when sizeof is applied to the name of a static array identifier (not allocated through malloc()/calloc()), the result is the size in bytes of the whole array rather then just address. That is equals to size of each elements multiply by the length of array.
In other words: sizeof(intArray) = 11 * sizeof(int) ( as intArray length is 11 ). So suppose if sizeof(int) is 4-bytes then sizeof(intArray) is equals to 44.
Below a code example and its output will help you to understand further(read comments):
int main(){
int intArray[11] = {1, 2, 8, 12, -13, -15, 20, 99, 32767, 10, 31};
int i = 0;
printf("sizeof(intArray): %d\n",
sizeof(intArray) //1. Total size of array
);
printf("sizeof(intArray[0]): %d\n",
sizeof(intArray[0]) //2. Size of one element
);
printf("length: %d\n",
sizeof(intArray) / sizeof(intArray[0]) //3. Divide Size
);
return 0;
}
Output:
sizeof(intArray): 44 //1. Total size of array: 11 * 4 = 44
sizeof(intArray[0]): 4 //2. Size of one element: 4
length: 11 //3. Divide Size: 44 / 4 = 11
One can check the working code #ideone, note: I am assuming size of int is 4.
Now notice as sizeof(intArray) is 44 that is more then length of array hence the condition is wrong and you have Undefined behavior in the code at runtime. To correct it replace:
for(i=0; i < sizeof(intArray); i++)
// ^--replace-----^
// wrong condition = 44
With:
for(i=0; i < sizeof(intArray) / sizeof(intArray[0]); i++)
// ^------------------------------------^
// condition Corrected = 11
To calculate length of array, I simply divided total size of array by the size of one element and code is:
sizeof(intArray) / sizeof(intArray[0]) // 44 / 4 = 11
^ ^
total size of size of first element
array

sizeof gives you the size of the array in bytes, not elements. To get the number of elements, divide by the size of only one element:
for(i = 0; i < (sizeof intArray / sizeof intArray[0]); i++)
{
printf("%d\n", intArray[i]);
}
It's worth noting that this only works for array types, it doesn't work when you have allocated a block of memory using malloc.

You need to change sizeof(intArray) to
sizeof(intArray)/sizeof(int)
This will give the number of the array elements.

Update
for(i=0;i<sizeof(intArray);i++)
to
for(i=0;i<sizeof(intArray)/sizeof(intArray[0]);i++)
sizeof(intArray) gives total size of array in bytes not number of elements in the array.

You have declared intArray as an array of 11 ints. Each int occupies a certain number of bytes in memory (typically four). So the size of the whole intArray is 11 * 4 = 44 bytes.
When you say i < sizeof(intArray), you are therefore saying i < 44. But your array has only 11 elements, not 44! So your loop will continue past the array bounds. It will continue to read four-byte chunks and interpret them as integers, and print out the garbage values.
That is why all the answers are saying that you need to have your loop condition be
i < sizeof(intArray) / sizeof (intArray[0])
You need to divide the size of the entire array by the size of a single element to get the number of elements in the array. Since you already know the number of elements, you could keep it simpler and just say
i < 11
but for more general cases where you might not know the size of the array, you need to use the other suggested loop condition.

Related

how to find the number of elements present in an array in C

suppose I have an array a[10] and it is filled up to 6 places example a[]={10,20,30,40,50,60} now rest 4 places are empty, now how do I print the number of places that are filled in an array-like in the above case it should print 6, given the scenario that I do not know the array beforehand like I do not have any clue what size it is or the elements that are there inside.
int a[]={10,20,30,40,50,60} initilizes all 6 elements.
int b[10]={10,20,30,40,50,60} initilizes all 10 elements, the last ones to 0.
There is no partial initialization in C.
There is no specified "empty".
to find the number of elements present in an array in C
size_t elemnt_count_a = sizeof a / sizeof a[0]; // 6
size_t elemnt_count_b = sizeof b / sizeof b[0]; // 10
I do not know the array beforehand
In C, when an array is defined, its size is known.
if the array is a[]={10,20,30,40,50,60}
here is my psedocode -
int size = 0;
if(i = 0; i < a.length(); i++) {
if(a[i] != null)
size++
}
the value of size should print 6

C program to subtract differing numbers from an array

I want to crate a program that will subtract a decreasing set of numbers. or in other words:
I an array i have the numbers {20,23,67,3,67,12,24}
There are 7 elements in the array so therefore i want to to this:
20 - 7
23 - 6
67 - 5
3 - 4
67 - 3
12 - 2
24 - 1
I would assume I need to use a loop but am not sure of how to do this.
In C there is no specific count of items for arrays, length is fixed. If do you know the size 7 and create the array with the fixed length you can use the below code. You can use pointers for dynamic length arrays, but it is complicated.
int a[7] = {20,23,67,3,67,12,24};
int i;
for(i=7;i>0;i--) {
printf("%d - %d \n", a[i-1], i);
}
You can start a counter at 0 and go through the array until you hit the null terminator and it will print your array in a the order in which it is stored as.

Count the number of initialized elements in an array in C

My array is:
int array[100];
If I initialize the first n elements (n < 100) with integers including 0, and the rest is uninitialized, how do I calculate n?
I tried a normal while loop with the following codes:
int i = 0;
int count = 0;
while (a[i++])
count++;
However, the problem with these codes is that it doesn't count the element of value 0 (it takes 0 as FALSE). How do I overcome this problem?
UPDATE: below is the background of this question
I have the following code:
int a[100];
int i;
for (i = 0; i < 100; i++)
scanf("%d", &a[i]);
If I have to input (just an example):
1 0 1 0 1 *
Then the first 5 elements of the array will be: 1 0 1 0 1. The rest will be uninitialized. In this situation, how do I count the number of these initialized elements to get 5?
If you can't simply record how many elements have been initialized, then you need to use a "magic" value like INT_MIN (the largest negative int) to know when an element is not used. Alternatively, instead of storing ints, store something like this:
struct element {
int value;
int flags; // 0 means not used
};
Oh, one more idea: store the count of initialized elements in the first element. This is sort of how malloc() works sometimes. Then you can make the array have 101 elements and pass (array + 1, array[0]) to functions which expect an array of size 100.

dynamic array with unknown size

I want to write a program in C where the user types in 2 numbers a and b.
0 < a < INT_MAX
a < b < INT_MAX
The program checks how many Prime numbers are in between a and b and saves all of them in a dynamic array.
For the malloc function I need the size of the array, which means I have to first check all numbers if they are prim numbers just to get the size of the array,
then use malloc(),
and then check all numbers again to fill the array.
Is there any possibility to make this run faster and not doing the same thing twice?
for (int i = a; i <= b; i++)
{
if (check_if_prime(i) == 0)
size++;
}
primze_numbers = malloc(size*sizeof(int));
int j = 0;
for (int i = a; i <= b; i++)
{
if(check_if_prime(i) == 0)
{
prime_numbers[j] = i;
j++;
}
}
Since the size is unknown in the beginning, allocating the space for the size of one more element is inefficient.
One possible solution is: reallocate the space(Use realloc) twice the size of the previous size whenever the size is not enough.
Real size - Space size
0 0
1 1
2 2
3 4
4 4
5 8
6 8
7 8
8 8
9 16
10 16
... ...
This way, the times of reallocation is not much, and you don't waste much space.
If you are able to use c++ - you can use std::vector which solves your problem.

c beginner, vectors

I'm a c beginner and i've a problem (as usual). I wrote this simple program:
#include <stdio.h>
#define SIZE 10
main()
{
int vettore[9];
int contatore1,contatore2;
for(contatore1 = 0; contatore1 <= 9; ++contatore1)
{
vettore[contatore1] = contatore1*2;
}
printf("%d\n\n", vettore[9]);
for(contatore2 = 0; contatore2 < 10; ++contatore2)
{
printf("%d\n", vettore[contatore2]);
}
printf("\n%d\n", vettore[9]);
return 0;
}
The output of this program is:
18
0
2
4
6
8
10
12
14
16
9
10
Why the value of vettore[9] changes 3 times? And why it has the correct value only on the first line of the output? thank you :)
C arrays are zero based so valid indexes for a 9 element array are [0..8]. You are writing beyond the end of your array. This has undefined results but is likely corrupting the next stack variable.
In more detail... vettore has 9 elements, which can be accessed using vettore[0] ... vettore[8]. The final iteration of your first loop writes to vettore[9]. This accesses memory beyond the end of your array. This results in undefined behaviour (i.e. the C standard does not specify expected outcome here) but it is likely that the address of vettore[9] is the same as the address of contatore2, meaning that the latter variable is written to.
You have a similar problem in the next loop which prints more elements than vettore contains.
You can fix this by changing your loops to
for(contatore1 = 0; contatore1 < 9; ++contatore1)
for(contatore2 = 0; contatore2 < 9; ++contatore2)
Note that it would be safer if you changed to calculating the size of the array instead, by using sizeof(vettore)/sizeof(vettore[0]) in the exit test of your loops in place of hard-coding 9.
Your array vettore has 9 elements, but by referencing vettore[9], you're actually referencing the 10th element (since element indexing starts from 0). So it's some random location on the stack, without a well-defined value.
The solution is to index only up to vettore[8], or define vettore to have size 10.
check this out:
for(contatore2 = 0; contatore2 < 10; ++contatore2)
{
printf("%d\n", vettore[contatore2]);
}
you are displaying 11 elements of the vettore array (which is defined as a 9 ints array). I think that the error is in the random allocation on the stack
the vettore size as you defined is 9
int vettore[9];
and in your loop you start from 0 till 9 so you are playing with 10 elements of the array and not 9 (size of the array)
you should define the array with size 10
int vettore[10];
Arrays (i.e. "vectors") start at index zero NOT one; it's contents may be, for example, 5 but it will occupy index locations of 0,1,2,3,4....
[1][2][3][4][5] <- Five items
0 1 2 3 4 <- Their respective locations in the array
Same goes for visualizing characters in strings.....(technically the location in memory contains ASCII value-- look into that for fun ;) )
['c']['a']['t'] <- Three items
0 1 2 <- Their index location in the array
I suggest Kochan's C Programming book; great for starting out!!!

Resources