Reputation: 2063
I created an array and put the value into array as follow
int *ptr_int;
int list_int[10];
int i;
for (i=0; i<10; i++)
list_int[i] = i + 1;
and I assign a value into list_int
array like this
list_int[17] = 18;
When I tried to get the count of array as follow
int size = sizeof(list_int ) / sizeof( int );
printf( "The size of int is %d.\n", size);
the result is only 10
.
How could I get the array room count?
Upvotes: 0
Views: 135
Reputation: 104
To Create Dynamic arrays ( allocated at run time )
int n;
scanf("%d",&n); // read n from the user at run time
int* x=(int*)malloc(sizeof(int)*n); // where n is the number of elements you need to allocate
////// after that you can access the array (x) using indexer
///// reading loop
for(int i=0;i<n;i++)
scanf("%d",&x[i]);
===============================================================================
Note: if you need more dynamic data structure which can allocate memory for each entry you can use linked lists
Upvotes: 1
Reputation: 122373
list_int[17] = 18;
This is undefined behavior because the array size is only 10.
Note that with the exception of variable length arrays, sizeof
operator is a compile time operator. The result of sizeof(list_int )
and sizeof(int)
are determined in compile time.
To implement an array with dynamic size, you need to allocate the array dynamically, you may find realloc
pretty helpful.
Upvotes: 1
Reputation: 43518
You have already defined the max size of your array as 10 with the following definition
int list_int[10];
You can not assign value to list_int[17]
. Becacuse list_int[17]
is out of the memory of the array list_int[10]
that you have defined.
You can only assign value to the element from 0 .. 9
Upvotes: 1
Reputation: 182609
the result is only 10.
That's the real size. Assigning to list_int[17]
is undefined behavior, and it does not magically extend the array.
Upvotes: 6