Sizeof(Array) Prints wrong value [duplicate] - c

This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
Closed 6 years ago.
I have initialized an array of size 10 but on printing the sizof array shows 40 . The code is as follows ,
#include <iostream>
using namespace std;
int main() {
int arr[10] = {2,4,5,6,7,8,9,6,90};
printf("%d \n" , sizeof(arr));
}
Output :
/Users/venkat/Library/Caches/CLion2016.1/cmake/generated/InsertionSort-e101b03d/e101b03d/Debug/InsertionSort
40
Process finished with exit code 0
What does C prints 40 here ?

sizeofreturns the size of the array in memory, not the length of the array. Then since sizeof(int) is 4 bytes and your array has 10 int values, its size is 40.

Your array contain 10 ints.
10 * sizeof(int)
int here is 32 bits = 4 bytes.
4*10 = 40. Simple math

Because sizeof is a built in operator that works on the type of the expression. For arrays (and not pointers) it will print sizeof(array_element_type) * array_length.
On your system, it must be that sizeof(int) is 4.
And once you get excited over learning that
sizeof(array)/sizeof(array[0]) == array_length
bear in mind that once you pass the array into a function, it will decay to a pointer and that will no longer hold.

You need to divide sizeof (arr) by the size of one element:
sizeof (arr)/ sizeof (arr[0])
This because sizeof(arr) shows the number of bytes the argument is made of, i.e. sizeof(int) * array dimention

Related

Printing an array gives me more values than what the array actually has

I tried to create a simple program that prints out the whole array but the program gives some values that aren't even in the array. Why is that and how can I fix it?
code:
#include <cs50.h>
#include <stdio.h>
int main (void)
{
int array[]={1,2,3,7};
int len=sizeof(array);
for(int i=0;i!=len;i++)
{
printf("%i\n",array[i]);
}
}
output that I want:
1
2
3
7
what I get:
1
2
3
7
-1483754768
32766
0
0
4195904
0
-953930857
32541
1
0
-1483754760
32766
So as you can see it prints out the values I placed inside the array but it also prints out a lot of values I never placed in it.
Sizeof() returns the size in BYTES of the array. So it will return 4bytes*4cells =16 bytes. Then because you are storing it in an integer variable it will convert it to decimal. What you have to do is sizeof(array)/sizeof(int) and it will give you the precise number of cells of the array
sizeof gives you size in bytes. To have number of array elements you need to divide it by size of the array element
int len=sizeof(array) / sizeof(array[0]);
There are 2 problems with your code:
len=sizeof(array); sizeof() returns number of bytes of memory. One int requires 2 or 4 bytes of memory depending on the compiler. In your case, the array has 4 integers. Therefore, sizeof(array) will give you 16(4*4) instead of 4, which you were expecting.
The solution is len=sizeof(array)/size(int); and this will give you the number of items in the array
This one is not actually a problem.
for ( init; condition; increment ) {
statement(s);
}
I’m suggesting you to change your condition a little bit for readability in the for loop in which you should use for(int i=0;i<len;i++). It’s not common for programmers to use i!=len Don’t get me wrong both ways work fine but most programmers prefer i<10
I hope it helps :) Happy Coding
If you have an array declared like
T array[N];
where T is the type of elements of the array and N is the number of elements then sizeof( array ) is equal to N * sizeof( T ) and yields the size of the extent of the memory occupied by the array.
So for this declaration
int array[]={1,2,3,7};
int len=sizeof(array);
sizeof( array ) is equal to 4 * sizeof( int ) and if sizeof( int ) is equal to 4 then sizeof( array ) is equal to 16.
But in the loop you need the number of elements not the size of the memory occupied by the array.
So you should write for example
size_t len = sizeof( array ) / sizeof( int );
Pay attention to that the type of an expression with the sizeof operator has the type size_t.
You may use your approach with the calculation of the number of elements in an array the following way
size_t len=sizeof(array);
provided that the array array has the element type char like
char array[] = { '1', '2', '3', '7' };
because sizeof( char ) is always equal to 1. So sizeof( array ) / sizeof( char ) is equivalent to sizeof( array ).
If you want to store the length of the array in the len variable. What you have to do!
The sizeof() operator can be used to find the length of an array.
Then dividing it by the size of one element of the array.
Show the len.
For example:
#include <stdio.h>
int main (void)
{
int array[]={1,2,3,7};
int len=sizeof(array)/sizeof(array[0]);
for(int i=0;i!=len;i++)
{
printf("%i\n",array[i]);
}
}
Read more find the length of an array

Array size mismatch - C [duplicate]

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.

Segmentation fault error array in c [duplicate]

This question already has answers here:
Getting a stack overflow exception when declaring a large array
(8 answers)
Closed 4 years ago.
I want to write a program in which I want to initialize integer array of size 987654321 for storing values of 1 and 0 only,
here is my program
#include <stdio.h>
#include <stdlib.h>
int main(){
int x,y,z;
int limit = 987654321;
int arr[limit];
for (x = 0;x < limit;x++){
printf("%d \n",arr[x]);
}
return 0;
}
but it gives segmentation fault
987654321 is certainly too big for a local variable.
If you need a dynamically sized array of that size you need to use malloc like:
int limit = 987654321;
int *arr = malloc(limit * sizeof(*arr));
if (arr == NULL)
{
... display error message and quit
}
...
free(arr); // free it once you're dont with the array
BTW are you aware that your array uses roughly 4 gigabytes of memory assuming the size of int is 4 on your platform?
Since you want to store values of 1 and 0 only, and these values require only one bit, you can use a bit array instead of an integer array.
The size of int is 4 bytes (32 bits) usually, so you can reduce the memory required by a factor of 32.
So instead of about 4 GB, you will only need about 128 MB of memory. Resources on how to implement a bit array can be found online. One such implementation is here.

Array becomes larger than declared [duplicate]

This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
Closed 5 years ago.
I'm writing a function that is supposed to split a string on "-" and return and array containing the parts from the string, so if the string is:
2017-10-23
I want the array to have three elements populated like:
arr[0] = 2017, arr[1] = 10, arr[2] = 23
This is the function:
/*
* return a array of the parts of date_string
*/
int * to_date_array(char *date_string)
{
int i = 0;
int f = 0;
char *tokens = strtok(date_string, "-"); /* get initial token */
static int arr[3] = {0, 0, 0};
char *ptr;
int val;
/* init static arr */
for (f = 0; f < sizeof(arr); f++)
arr[f] = 0;
/* do the split */
while (tokens != NULL) {
val = strtol(tokens, &ptr, 10);
arr[i++] = val;
tokens = strtok(NULL, "-");
}
/*
* for some reason arr becomes 12 elements long?
* I expected it to have 3 elements
*/
puts("func: to_date_array");
puts("------------------------");
for (f = 0; f < sizeof(arr); f++)
printf("arr[%d]: %d\n", f, arr[f]);
return arr;
}
The function works but I'm really puzzled by the "arr" array. I expect it to be three elements long but when I iterate through it and print every element, it show 12 elements?
$ gcc -Wall main.c arguments.c -o timespan
$ ./timespan 2015-08-10 2017-10-18
func: to_date_array
------------------------
arr[0]: 2015
arr[1]: 8
arr[2]: 10
arr[3]: 0
arr[4]: 0
arr[5]: 0
arr[6]: 0
arr[7]: 0
arr[8]: 0
arr[9]: 0
arr[10]: 0
arr[11]: 0
The sizeof operand returns a size in bytes (where by definition a char takes one byte). On your (and mine) machine, sizeof(int) is 4, hence an array of 3 int takes 12 bytes. See nucleon's answer.
Your to_date_array is not reentrant. It would be nicer to return a dynamically allocated array (e.g. with calloc ....). Of course you need then to adopt the convention that its result has to be later free-d (e.g. by the caller).
You could consider also returning a pointer to some struct ending with a flexible array member.
You could also pass arr (and its length) to the to_date_array and have it been filled by that function.
sizeof computes the size of the array in bytes, thus you have to divide by the size of a single element to get the number of elements, thus use
sizeof(arr)/sizeof(*arr)
sizeof returns the number of bytes in the array, not the number of elements. On your system, an int is 4 bytes wide, so the array takes up 12 bytes.
You need to divide the size of the array by the size of a single element to get the number of elements:
sizeof arr / sizeof *arr
C does not do any bounds checking on array access - the array is only three elements wide, but you won't get any sort of OutOfBounds exception if you attempt to access elements outside of that range. The behavior is undefined - your code may crash, it may produce unexpected results, it may work as intended, but the results won't necessarily be repeatable or predictable.
sizeof int arr[3] is sizeof(int) * 3 equals to 4*3 = 12

sizeof dynamic array is not correct [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 7 years ago.
In array there are four element so it size should be 4bit*4 = 16. (An int data type take 4 bit in my system to store the value.) But when i ran this code i only got 8 bit as the size of dynamicArray.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//Dynamic arrays save memory by creating a pointer that stores
//the beginning of the array
int *dynamicArray = malloc(20 * sizeof(int));
*dynamicArray = 10;
printf("Address %x stores value %d\n", dynamicArray, *dynamicArray);
dynamicArray[1] = 20;
printf("dynamicArray[1] stores value %d\n", dynamicArray[1]);
dynamicArray[2] = 45;
printf("dynamicArray[2] stores value %d\n", dynamicArray[2]);
dynamicArray[3] = 34;
printf("dynamicArray[3] stores value %d\n", dynamicArray[3]);
printf("The size of dynamicArray is %d\n", sizeof(dynamicArray));
// Release unused memory:
free(dynamicArray);
return EXIT_SUCCESS;
}
Here is the image of output.
Also suggest me website for C to check the in-built function properties or to know about them more.
Thank you.
You don’t have an array; you have a pointer.
The size of the pointer is measured in bytes, not bits.
sizeof is evaluated at compile time and is constant for any given expression or type. It does not depend on the number of “filled” elements in an array (or pointer to some space that holds those elements, for that matter).
Your expression is equivalent to sizeof(int*), and pointers are 8 bytes in your environment.
I ran your code on my 32-bit computer and the value of sizeof(dynamicArray) does report 4. I bet your computer is 64-bits which is why the value is 8 instead.
Take a look at: http://www.viva64.com/en/a/0004/ and look for the table titled "Table N2. 32-bit and 64-bit data models.". That would help explain why some systems report 4 and some report 8 for the value for sizeof(dynamicArray).

Resources