Example array:
int hourlyTemperatures[ 24 ];
So in function call we write the array name and its size!
modifyArray( hourlyTemperatures, 24 )
we know the above mentioned is the right way to pass array to function!
but in this code below I see we are calling mean function and passing array without giving its element size like mean (response);
So my question is which one is correct? Passing array with its element size or just passing array with itβs name? And why the two method is used?
#include<stdio.h>
#define SIZE 99
void mean(const unsigned int answer[]);
int main(void)
{
unsigned int response [SIZE] =
{6,7,8,9,8,7,8,9,8,9,7,8,9,5,9,8,7,8,7,8,6,7,8,9,3,9,
8,7,8,7,7,8,9,8,9,8,9,7,8,9,6,7,8,7,8,7,9,8,9,2,7,8,
9,8,9,8,9,7,5,3,5,6,7,2,5,3,9,4,6,4,7,8,9,6,8,7,8,9,
7,8,7,4,4,2,5,3,8,7,5,6,4,5,6,1,6,5,7,8,7
};
mean (response);
}
void mean (const unsigned int answer[])
{
size_t j;
unsigned int total = 0;
printf("%s\n%s\n%s\n", "********", "Mean", "********");
// total response values
for(j=0; j<SIZE; ++j){
total += answer[j];
}
printf ("The mean is the average value of the data items!\n"
"The mean is the equal to the total of all data items\n"
"divided by the number of data items (%u)\n\n", SIZE);
printf("The mean value for this run is: %u / %u = %.4f\n\n", total, SIZE, (double)total/SIZE );
}
The function call modifyArray(hourlyTemperatures, 24) passes a pointer to the first int stored in the array hourlyTemperatures[], so the function knows where to find the first value, and the int 24, so the function knows how big the array is to avoid walking off the end of the array.
The function call mean(response) passes a pointer to the first unsigned int stored in the array response[], but the function needs another way to know how large the array is, since no further information is passed by the caller.
The preprocessor directive #define SIZE 99 is used when you compile the program, and any occurrence of the characters 'SIZE' is replaced with the characters '99' in the source before the actual compilation, so the function is interpreted with the line:
for (j = 0; j < 99; ++j) {...
In this way the mean() function knows how large the array is. Instead of using the #define, you could also put the line:
int size = 99;
before the function definitions. This would make size a global variable visible in any function below it, so you could write:
for (j = 0; j < size; ++j) {...
But, since global variables are generally a bad thing, you should usually pick the first method, explicitly passing the size of the array to the function that processes the array.
So, to recap:
1) It is usually best to pass the size of the array explicitly to the processing function: modifyArray(hourlyTemperatures, 24). This way you always know what size the array is, and you can work with arrays of different sizes: modifyArray(hourlyTemperatures, 25), for example, if you have added a temperature measurement.
2) You can define a constant to store the size of the array, which is then used in the array processing function: #define SIZE 99. One downside of this is that if you want to work with an array with 100 elements, you have to change the source code so that #define SIZE 100, and then recompile.
3) You can declare a global variable to store the size of the array, and use the global variable in the array processing function. The global variable is accessible to any function below the declaration in the source file. This method is error-prone: another function might inadvertently change the value of size, giving you a nasty surprise when you call mean().
One last thing-- a string is an array of chars, but not just any old array of chars: it must be null-terminated. This means that the last character of a string must be '\0'. Functions that process strings don't need to know the size of the strings (even though a string is an array), because that information is implicit in a string. You can count the number of characters before the '\0' (or just use strlen()), or just process characters sequentially until you reach the end.
Related
This is well known code to compute array length in C:
sizeof(array)/sizeof(type)
But I can't seem to find out the length of the array passed as an argument to a function:
#include <stdio.h>
int length(const char* array[]) {
return sizeof(array)/sizeof(char*);
}
int main() {
const char* friends[] = { "John", "Jack", "Jim" };
printf("%d %d", sizeof(friends)/sizeof(char*), length(friends)); // 3 1
}
I assume that array is copied by value to the function argument as constant pointer and reference to it should solve this, but this declaration is not valid:
int length(const char**& array);
I find passing the array length as second argument to be redundant information, but why is the standard declaration of main like this:
int main(int argc, char** argv);
Please explain if it is possible to find out the array length in function argument, and if so, why is there the redundancy in main.
sizeof only works to find the length of the array if you apply it to the original array.
int a[5]; //real array. NOT a pointer
sizeof(a); // :)
However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.
int a[5];
int * p = a;
sizeof(p); // :(
As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)
There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?
A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)
A second idea is storing the array length next to the array, just like any modern programming language does:
a -> [5];[0,0,0,0,0]
But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:
struct {
size_t length;
int * elements;
}
Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
As stated by #Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.
Third, C doesn't have references so your usage of & in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
Regarding int main():
According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).
That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.
Hence, size calculation is performed by a function which is a trivial modification of strlen().
argc is only there to make argv length calculation O(1).
The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.
This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:
void func(int A[])
// should be instead: void func(int * A, const size_t elemCountInA)
They are very few cases, where you don't need this, like when you're using multidimensional arrays:
void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:
void vec_add(float out[3], float in0[3], float in1[3])
is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):
void vec_add(float * out, float * in0, float * in1)
If you were to use C++, then you can actually capture the array size and get what you expect:
template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
for (size_t i = 0; i < N; i++)
out[i] = in0[i] + in1[i];
}
In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.
int arsize(int st1[]) {
int i = 0;
for (i; !(st1[i] & (1 << 30)); i++);
return i;
}
This works for me :)
length of an array(type int) with sizeof:
sizeof(array)/sizeof(int)
Best example is here
thanks #define SIZE 10
void size(int arr[SIZE])
{
printf("size of array is:%d\n",sizeof(arr));
}
int main()
{
int arr[SIZE];
size(arr);
return 0;
}
This is well known code to compute array length in C:
sizeof(array)/sizeof(type)
But I can't seem to find out the length of the array passed as an argument to a function:
#include <stdio.h>
int length(const char* array[]) {
return sizeof(array)/sizeof(char*);
}
int main() {
const char* friends[] = { "John", "Jack", "Jim" };
printf("%d %d", sizeof(friends)/sizeof(char*), length(friends)); // 3 1
}
I assume that array is copied by value to the function argument as constant pointer and reference to it should solve this, but this declaration is not valid:
int length(const char**& array);
I find passing the array length as second argument to be redundant information, but why is the standard declaration of main like this:
int main(int argc, char** argv);
Please explain if it is possible to find out the array length in function argument, and if so, why is there the redundancy in main.
sizeof only works to find the length of the array if you apply it to the original array.
int a[5]; //real array. NOT a pointer
sizeof(a); // :)
However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.
int a[5];
int * p = a;
sizeof(p); // :(
As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)
There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?
A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)
A second idea is storing the array length next to the array, just like any modern programming language does:
a -> [5];[0,0,0,0,0]
But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:
struct {
size_t length;
int * elements;
}
Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
As stated by #Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.
Third, C doesn't have references so your usage of & in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
Regarding int main():
According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).
That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.
Hence, size calculation is performed by a function which is a trivial modification of strlen().
argc is only there to make argv length calculation O(1).
The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.
This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:
void func(int A[])
// should be instead: void func(int * A, const size_t elemCountInA)
They are very few cases, where you don't need this, like when you're using multidimensional arrays:
void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:
void vec_add(float out[3], float in0[3], float in1[3])
is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):
void vec_add(float * out, float * in0, float * in1)
If you were to use C++, then you can actually capture the array size and get what you expect:
template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
for (size_t i = 0; i < N; i++)
out[i] = in0[i] + in1[i];
}
In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.
int arsize(int st1[]) {
int i = 0;
for (i; !(st1[i] & (1 << 30)); i++);
return i;
}
This works for me :)
length of an array(type int) with sizeof:
sizeof(array)/sizeof(int)
Best example is here
thanks #define SIZE 10
void size(int arr[SIZE])
{
printf("size of array is:%d\n",sizeof(arr));
}
int main()
{
int arr[SIZE];
size(arr);
return 0;
}
Initialize a global 1D array "StudentData" of type char with your ID (5 digits).
Using pointers syntax is mandatory in this part.
Can you give me some tips about doing that?
I tried doing this,
char *StudentData;
void loadData(){
StudentData=(char*)"60897";
}
Is it right or should I try doing something else?
You probably want something along the lines of:
#include <string.h> //This header has strcpy()
#define ENOUGH_DIGITS 5 //This is so you can easily modify ID length in the future
char StudentData[ENOUGH_DIGITS+1]; //Global array 1 bigger than the longest string
void loadData(){
//Ask the compiler to put a read-only string somewhere in the data memory
const char *myID = "60897";
//Copy the read-only string into the global array
strcpy(StudentData,myID);
}
While you are indeed using an array (the string literal actually is one), it is an anonymous one β and your studentData is only a pointer to that one.
a global 1D array "StudentData"
I would rather interpret this as you are intended to have a true array with that name, so that would look like:
char studentData[N];
where N is a constant expression representing an appropriate size for your array, at least 5 as you need to be able to store 5 digits β possibly 6 if your ID should be represented as a C-string (such one needs one additional character holding the mandatory null-terminator!), or you go with a power of two right away (8 minimally).
Using pointers syntax is mandatory in this part.
So you'll need a pointer to that array:
char* ptr = studentData;
You could now just use the pointer to assign values to:
*ptr++ = '0'; // dereferences the pointer, assigns a value to (in this
// case a character representing the digit zero) and
// increments it afterwards to point to the next character
// repeat this for the next four digits!
*ptr++ = 0; // terminating null character (note: no single quotes)
// or:
*ptr = 0;
// it's up to you to decide if incrementing yet another time actually
// is meaningful (first variant) or unnecessary (second variant)...
If there are no further requirements given you might have this code directly in main function or as a little bonus place it in another function being called from main like:
void loadData(size_t size, char data[size])
{
// ideally size check with appropriate error handling
// assignment as above
}
// in main:
loadData(sizeof(studentData), studentData);
Note: For function parameters all of char* data, char data[] or char[someArbitrarySize] are equivalent, if any size is given, it is simply ignored β we still can add it for documentation purposes, in above signature: to tell that an array with a size of (at least) size is expected. Note, too, that if there are more than one dimensions given this only applies for the outer most dimension, though!
1D array "StudentData"
No no no. StudentData is not an array, it's a pointer. Arrays are blocks of memory while pointers are addresses to memory, which may or may not be an array. An array sometimes becomes a pointer, that's called decay.
"60897" is already a char * compatible. You can directly assign it to StudentData. Like this:
StudentData = "60897";
If you want to use an array, do this:
#include <string.h>
char StudentData[WHATEVER_IS_ENOUGH_TO_HOLD_THE_DATA]; /* allocate array.
make sure that the size of the array accounts for the null
terminating character. */
void loadData(){
strcpy(StudentData, "60897"); //you can't directly assign to an array.
}
I am having trouble finding a way to get the array size from within a function. Here is my code:
#include <stdio.h>
void printBuff(char *buf);
int main()
{
char arr[12] = "csdlnclskjn";
printf("Array size: %d, element size: %d. ",sizeof(arr), sizeof(arr[0]));
printBuff(arr);
return 0;
}
void printBuff(char *buf){
printf("Array size: %d, element size: %d.",sizeof(buf), sizeof(buf[0]));
}
As seen above, printBuff does the same as the second line in the main function. However, the outputs are different:
Array size: 12, element size: 1. Array size: 4, element size: 1.
Thinking about it, I understand why the output is 4 in the printBuff() method. In fact, arr is a pointer to the first element of the array. On a 32-bit architecture, sizeof(arr) will then return 4, on 64-bit one it will return 8. What I do not understand is why sizeof(arr) returns the size of the array instead of the number of bytes of the pointer when used in the main() function. After all, arr, when invoked inside main(), is still a pointer, right?
So my questions are:
How come sizeoff() is interpreted differently depending on the context in which it is used? What does this depend on?
How to get the actual array size (number of elements in array) from within a function, without passing the size as an argument, without using methods such as iterating over the array while incrementing a counter until '\0' is reached - just the simplest way to get array size regardless of the context.
Incidentally, where does the compiler/system responsible for remembering the size of the array store the size of the array? How is it associated with the array and how is it retrieved?
I wanted to iterate though an array using sizeof(buf), / sizeof(buf[0]) as the size of the array but apparently that is not possible.
so here are my answers for your questions:
The array is "converted" into char* type when passed into the function (with the char* parameter).
AFAIK there is no such way. You could use strlen function for strings. Otherwise, you have to pass the length as parameter.
See How does an array pointer store its size?
Don't use sizeof(buf)/sizeof(buf[0]) to get length of an array when passing array parameters. See this. for more information.
This is well known code to compute array length in C:
sizeof(array)/sizeof(type)
But I can't seem to find out the length of the array passed as an argument to a function:
#include <stdio.h>
int length(const char* array[]) {
return sizeof(array)/sizeof(char*);
}
int main() {
const char* friends[] = { "John", "Jack", "Jim" };
printf("%d %d", sizeof(friends)/sizeof(char*), length(friends)); // 3 1
}
I assume that array is copied by value to the function argument as constant pointer and reference to it should solve this, but this declaration is not valid:
int length(const char**& array);
I find passing the array length as second argument to be redundant information, but why is the standard declaration of main like this:
int main(int argc, char** argv);
Please explain if it is possible to find out the array length in function argument, and if so, why is there the redundancy in main.
sizeof only works to find the length of the array if you apply it to the original array.
int a[5]; //real array. NOT a pointer
sizeof(a); // :)
However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.
int a[5];
int * p = a;
sizeof(p); // :(
As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)
There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?
A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)
A second idea is storing the array length next to the array, just like any modern programming language does:
a -> [5];[0,0,0,0,0]
But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:
struct {
size_t length;
int * elements;
}
Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?
The array decays to a pointer when passed.
Section 6.4 of the C FAQ covers this very well and provides the K&R references etc.
That aside, imagine it were possible for the function to know the size of the memory allocated in a pointer. You could call the function two or more times, each time with different input arrays that were potentially different lengths; the length would therefore have to be passed in as a secret hidden variable somehow. And then consider if you passed in an offset into another array, or an array allocated on the heap (malloc and all being library functions - something the compiler links to, rather than sees and reasons about the body of).
Its getting difficult to imagine how this might work without some behind-the-scenes slice objects and such right?
Symbian did have a AllocSize() function that returned the size of an allocation with malloc(); this only worked for the literal pointer returned by the malloc, and you'd get gobbledygook or a crash if you asked it to know the size of an invalid pointer or a pointer offset from one.
You don't want to believe its not possible, but it genuinely isn't. The only way to know the length of something passed into a function is to track the length yourself and pass it in yourself as a separate explicit parameter.
As stated by #Will, the decay happens during the parameter passing. One way to get around it is to pass the number of elements. To add onto this, you may find the _countof() macro useful - it does the equivalent of what you've done ;)
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.
Third, C doesn't have references so your usage of & in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
Regarding int main():
According to the Standard, argv points to a NULL-terminated array (of pointers to null-terminated strings). (5.1.2.2.1:1).
That is, argv = (char **){ argv[0], ..., argv[argc - 1], 0 };.
Hence, size calculation is performed by a function which is a trivial modification of strlen().
argc is only there to make argv length calculation O(1).
The count-until-NULL method will NOT work for generic array input. You will need to manually specify size as a second argument.
This is a old question, and the OP seems to mix C++ and C in his intends/examples. In C, when you pass a array to a function, it's decayed to pointer. So, there is no way to pass the array size except by using a second argument in your function that stores the array size:
void func(int A[])
// should be instead: void func(int * A, const size_t elemCountInA)
They are very few cases, where you don't need this, like when you're using multidimensional arrays:
void func(int A[3][whatever here]) // That's almost as if read "int* A[3]"
Using the array notation in a function signature is still useful, for the developer, as it might be an help to tell how many elements your functions expects. For example:
void vec_add(float out[3], float in0[3], float in1[3])
is easier to understand than this one (although, nothing prevent accessing the 4th element in the function in both functions):
void vec_add(float * out, float * in0, float * in1)
If you were to use C++, then you can actually capture the array size and get what you expect:
template <size_t N>
void vec_add(float (&out)[N], float (&in0)[N], float (&in1)[N])
{
for (size_t i = 0; i < N; i++)
out[i] = in0[i] + in1[i];
}
In that case, the compiler will ensure that you're not adding a 4D vector with a 2D vector (which is not possible in C without passing the dimension of each dimension as arguments of the function). There will be as many instance of the vec_add function as the number of dimensions used for your vectors.
int arsize(int st1[]) {
int i = 0;
for (i; !(st1[i] & (1 << 30)); i++);
return i;
}
This works for me :)
length of an array(type int) with sizeof:
sizeof(array)/sizeof(int)
Best example is here
thanks #define SIZE 10
void size(int arr[SIZE])
{
printf("size of array is:%d\n",sizeof(arr));
}
int main()
{
int arr[SIZE];
size(arr);
return 0;
}