How to get count of elements in an array? - c

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?

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.

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

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.

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

Related

looping over an array in C

Say I want to loop over an array, so I used a basic for loop and accessed each element in it with the index but what happens if I don't know how long my array is?
#include <stdio.h>
#include <stdlib.h>
int main(){
int some_array[] = {2,3,5,7,2,17,2,5};
int i;
for (i=0;i<8;i++){
printf("%d\n",some_array[i]);
}
return 0;
}
This is just a simple example but if I don't know how big the array is, then how can I place a correct stopping argument in the loop?
In Python this is not needed since the StopIteration exception kicks in, but how can I implement it in C?
Just do like this:
for (i=0; i<sizeof(some_array)/sizeof(some_array[0]); i++){
printf("%d\n",some_array[i]);
}
But do beware. It will not work if you pass the array to a function. If you want to use it in a function, then write the function so that you also pass the size as argument. Like this:
void foo(int *arr, size_t size);
And call it like this:
foo(some_array, sizeof(some_array)/sizeof(some_array[0]));
But if you have a function that just take a pointer, there is absolutely no standard way to find out the size of it. You have to implement that yourself.
You have to know the size of the array. That's one of the most important rules of C programming. You, the programmer, are always responsible for knowing how large your array is. Sure, if you have a stack array or a static array, you can do this:
int array[size];
int size_of_array = sizeof array / sizeof *array;
for (int i = 0; i < size_of_array; i++) {
// do something with each array[i]
}
But as you can see, you needed the variable size in the first place. So what's the point of trying to discover the size if you were forced to know it already?
And if you try to pass this array to any function
some_function(array); /
you have to pass the size of the array too, because once the array is no longer in the same function that declared it, there is no mechanism to find its size again (unless the contents of the array indicate the size somehow, such as storing the number of elements in array[0] or using a sentinel to let you count the number of elements).
void some_function(int *array) {
/* Iterate over the elements until a sentinel is found.
* In this example, the sentinel is a negative number.
* Sentinels vary from application to application and
* implicitly tell you the size of the array.
*/
for (int i = 0; array[i] >= 0; i++) {
// do something with array[i]
}
}
And if it is a dynamically-allocated array, then you need to explicitly declare the number of elements anyway:
int size = 10;
int *array = malloc(sizeof *array * 10);
So, to summarize, you must always know the size of the array. There is no such thing in C as iterating over an array whose size you don't know.
You can use sizeof() to get the size of the array in bytes then divide the result by the size of the data type:
size_t n = sizeof(some_array)/sizeof(some_array[0]);
In general, you can calculate the size of the array with:
sizeof(ArrayName)/sizeof(ArrayType)
but this does not work with dynamically created arrays

How to know the array length and put it in an integer variable in C?

How can I know the array length and put it in an integer variable in C?
int array []={1,2,3,4,5};
int arrayLength = ???????? ;
int i;
for (i = 0; i < arrayLength ;i++){
printf("the i is :%i \n", i );
}
I would use:
const size_t arrayLength = sizeof array / sizeof *array;
The first sizeof array is the size (in bytes) of all of array, the second is the size of the first element and when divided that becomes the number of elements.
Sizes are good to keep as size_t, and of course it's const since it's not going to be changing.
Note that this code won't work if the array is passed into a function, since arrays decay into pointers in that case so you need a separate argument for the size.
array size is constant. and it must be known at compile time. so you know it and you can use it in your program.

function to insert an element in sorted array in C

I am new to C and was writing a function to insert an element to sorted list. But my code does not display the last digit correctly. Though i know there are variety of ways to correct it but i want to know why my code isnt working, here's the code
#include <stdio.h>
int insert(int array[],int val);
int main (void)
{
int arr[5],j;
for (j = 0; j<5; j++)
{
scanf("%d",&arr[j]);
}
insert(arr,2);
for(j = 0;j<6;j++)
printf("%d",arr[j]);
return(0);
}
int insert(int array[],int val)
{
int k,i;
for (k = 0;k<5;k++)
if(val<array[k])
break;
for (i = 4; i>=k;i--)
{
array[i+1] = array[i];
}
array[k] = val;
return(1);
}
You are writing out of the range of the array here:
for (i = 4; i>=k;i--)
{
array[i+1] = array[i];
Where i+1 == 5 and you array has a range of 0 ...
4
Then you try to print the array but you go out of bounds again:
for(j = 0;j<6;j++)
printf("%d",arr[j]);
First make sure your array is large enough.
When you give a static / auto array to a function for insertion of elements, you must give: Address, Valid length, and Buffer Space unless guaranteed large enough.
When giving a dynamically allocated array, you must give pointer and valid length, you might give buffer space or guarantee enough space left to avoid reallocations.
Otherwise, you risk a buffer overrun, and UB means anything may happen, as in your example.
You're trying to make arr[6] out of arr[5] adding one val - it's impossible in C using statically allocated arrays.
To accomplish what you're trying to do you'd need to use dynamical arrays allocation:
int *arr;
int N = 5;
arr = (int *)malloc(N*sizeof(int));
then you use this arr same way as you did with arr[5] for loading data here via scanf.
And later on , while adding extra value to array - you'd need to reallocate your arr to make it bigger (read about malloc/realloc C functions):
arr = (int *)realloc((N+1)*sizeof(int));
Now your arr is of 6 int-s size.
Unfortunately if you don't know array sizes (number of elements) a priori you would need to deal with dynamical memory allocations in C.
Don't forget to release that memory in the end of the main() function:
free(arr);
You have to increase your array size from 5 to 6 as you are inserting one new element in your array, so there should be some space for that.
int arr[6];
you can also find more information in the link below:
https://learndswithvishal.blogspot.com/2020/06/insert-element-in-sorted-array.html

initializing an array using a function in C

I am doing an assignment for class and I thought I would bug you all with a question:
So the purpose of the program is for the user to enter the size of the array and then initialize it with some data. Max size is 20. My issue is that the array crashes when the sets the size beyond 14 and tries to initialize it. So forexample, if it sets the size as 20, it accepts it, but when I try to initialize it, it crashes. I have no idea what I am doing. your help is much appreciated.
Thank you very much,
Essi
int main ()
{
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
//I have a piece a line or two of code that asks the user for the size of the
array
printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
do
{
printf("Enter array element %d : ", initCounter+1);
myArray[initCounter] = userInitArray();
initCounter++;
}while (initCounter < sizeOfArray);
}
float userInitArray()
{
float num;
scanf("%f", &num);
return num;
}
These two lines
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
Create an empty array. So whatever you try to store in this array later on is access out of bounds and invokes undefined behavior. The fact that your program crashes on 14th call is simply luck. It could have crashed on the first one just as well.
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
Your array is created here with a size of zero. It doesn't magically expand when you later increase sizeOfArray. You need to get the size variable set first (from your 'line or two of code' user input) then create the array based on that.
You may also want to impose some sensible upper limit on your array size so you don't blow up your stack when trying, for example, to create a one-billion-entry array :-)
You have a (variable-length) array of size zero. You need to first ask for the size, and then allocate the array. Otherwise any attempts to assign to array elements would result in undefined behaviour.
You could do :
int sizeOfArray; //size Of Array
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
float myArray[sizeOfArray]; // not a good practice
The right way to do it would be:
int sizeOfArray; //size Of Array
float *myArray;
printf("tell me the size of the array");
scanf("%d",&sizeOfArray);
myArray=malloc(sizeof(float)*sizeOfArray);
You may use the pointer as a common array then.
and call like this: myArray[3] = doSomething();
EDIT Note that since you already know the max size you could avoid doing dynamic allocations listed above:
#Define MAXSIZE 20
int main ()
{
int sizeOfArray; //size Of Array
float myArray[MAXSIZE];
printf("tell me the size of the array\n");
scanf("%d",&sizeOfArray);
printf("\nLet's Initialize an array of size %d!!\n", sizeOfArray);
do
{
printf("Enter the element at myArray[%d] : ", initCounter+1);
myArray[initCounter] = userInitArray();
initCounter++;
}while (initCounter < sizeOfArray);
}
float userInitArray()
{
float num;
scanf("%f", &num);
return num;
}
Probably this last option is what your teacher is actually looking for.
You need to read sizeOfArray before you allocate myArray dynamically like this:
float * myArray = malloc(sizeOfArray * sizeof(float));
This is allocating sizeof(float) * sizeOfArray bytes of memory on heap and assigning address of allocated memory to myArray.
This is maybe hard to understand about arrays in C, they are really just pointers into memory - in your program the array myArray is allocated statically on stack and is of size 0. You cannot add any elements to it or assign to any index, it will not grow, its forewer 0 float elements long. Best thing that can happen to your program in this case is that it will crash. Worst case, it will not crash and strange things will happen;
You really should read something about memory allocation/management in C.
I think you forget to add function prototype in the beginning of your program (before main).
And also
int sizeOfArray = 0; //size Of Array
float myArray[sizeOfArray];
is wrong.
As you are using variable length array (valid in C99), you can do it as
int sizeOfArray; //size Of Array
printf("Let's Initialize an array of size %d!!\n", sizeOfArray);
float myArray[sizeOfArray];
dynamic arrays are not supported in C or C++.
Change your array to:
float* myAraray;
//later when you have the size , allocate it:
myArray = (float*)malloc(arrSize * sizeof(float));

Int-stream in C

I'm implementing a function in C where I convert a byte[] to an int[]. The problem is that the length of the int[] depends on the contents of the byte[] (not just the length of the byte[]) so I won't know the total length of the int[] until I've iterated the entire byte[]. I'm therefore looking for some form av int-stream or dynamically increasing int-list which I can write to and then convert to a int[] once I'm done writing all the ints. My C-experience is a bit limited at the moment so I'm not really sure what's considered best practice to solve this kind of problem. Any suggestions?
The easiest method would be to allocate the int[] to be the same length (number of elements) as the byte[], and when you're done and know the size, call realloc to shrink it.
This assumes, of course, that interpreting the data would never create more integers than there are bytes in the stream.
There are a few ways of doing this I can think of.
I'm assuming, based on your question, that the transformation of your char[] to the corresponding int[]s is expensive (which is why you want to avoid performing that calculation twice - once to determine the size, and again to populate the contents.
So, here's how I would go about it:
First, is there a maximum size you can associate to the transformation? EX: Is there a maximum 2-to-1 size difference? (For each char in the char[] can it create "up to X" ints?)
If this is the case, and memory usage isn't an issue (you're not super constrained) - Go ahead and alloc the maximum size, populate it as you perform your translation, and realloc when you're done to shrink your memory footprint.
If this is not the case, you're in tougher waters, and should look to non-contiguous schemes - such as a linked list. Once you've performed your translation and built your linked list, you can then allocate space for your array, and visit each element in the linked list to populate the array.
First, inspect byte[] to determine the resulting int[] size. Then use malloc() to allocate the appropriately sized int[] structure.
#include <stdlib.h>
...
// imagine that the resulting int[] size depends on the sum of the bytes
int j, size = 0;
for (j = 0; byte[j]; ++j)
size += byte[j];
int *int_array = (int *) malloc (size);
for (j = 0; j < size; ++j)
int_array [j] = whatever;
First, If you can use C++, then you can just use a vector, which is a dynamically-sized array. Otherwise, you'll have to first iterate through your byte array to determine what the int array size should be, then dynamically allocate the int array. Second, C doesn't have a byte type, so the type normally used is char.
#include <stdlib.h>
char byte_array[ size ];
int i, int_size = 0;
int *int_array;
for ( i = 0; i < size; i++ ) {
int_size += f( byte_array[i] );
}
int_array = (int*) malloc( int_size );
where f() is some function you write that looks at one element of the byte array to help determine how large the int array should be.

Resources