I want to introduce as stated in the title, a binary search function to my program. But keep getting two errors which I have no clue how resolve.
This is the compiling-error I get for my code:
: expected expression before '{' token
array[size]={1,3,6,8,12,13,16};
^
upg10.8.c: In function 'binarySearch':
upg10.8.c:55:7: warning: control reaches end of non-void function [-Wreturn-
type]
}
^
Any idea to what is causing the problem in both cases?
You can find the code below:
#include <stdio.h>
#include <stdlib.h>
int binarySearch(int n, int array[], int search);
int main(void){
int search, size=7, array[size], middle;
array[size]={1,3,6,8,12,13,16};
printf("input search number:\n");
scanf("%d", &search);
middle = binarySearch(size, array, search);
if(middle ==-1){
printf("There is no index corresponding to that search number");
}
else{
printf("Index %d for Search%d", middle, search);
}
return 0;
}
int binarySearch(int n, int array[], int search){
int first =0;
int last = n-1;
int middle= (first+last)/2;
while(first<=last){
if(array[middle]<search)
first= middle +1;
else if(array[middle]==search){
return search;
}
else
last = middle -1;
middle = (first +last )/2;
return middle;
break;
}
if(array[first]>array[last])
return -1;
}
Remove the array[size]={1,3,6,8,12,13,16};. You cant initialize value to array after declaration. But only on the time of deceleration. The correct code is
int array[]={1,3,6,8,12,13,16};
Also declare size as macro constant. I think its better. It will look like
#define size 7
Everything else look fine!!
int search, size=7, array[size], middle;
Here you've defined the array object array. Note that the size is not a constant, so this is a VLA (variable-length array). Not all compilers support VLAs, and you don't need one here.
array[size]={1,3,6,8,12,13,16};
This is several kinds of wrong.
array[size] would be element 7 of array -- but array only has elements 0 through 6.
You obviously mean to assign the 7 values {1,3,6,8,12,13,16} to the 7 elements of array, but you can't do it this way. In fact, array objects can be initialized, but they can't be assigned to (for complicated historical reasons).
{1,3,6,8,12,13,16} is not an expression, so it can't appear on the right hand side of an assignment, regardless of what's on the left. It is a valid initializer.
Drop the definition of size and change the declaration of array to this:
int array[] = {1,3,6,8,12,13,16};
Since you've initialized array with 7 elements, you don't have to tell the compiler how many elements it has; the size is determined for you automatically. (That's one of the few things C will helpfully do for you.)
Now you could define
const int size = 7;
but then you'd have to carefully update the initializers for array and size together, and make sure they're consistent. Instead, you can compute the size:
const int size = sizeof array / sizeof array[0];
Related
I am learning recursion. As an exercise I am trying to find the maximum of an array recursively.
int recursive (int *arr, int n, int largest) {
if(n==0)
return largest;
else {
if (*(arr+n)>largest) {
largest = *(arr+n);
recursive(arr, n-1, largest);
}
}
}
int main() {
int length = n-1;
int largest = v[0];
int z = recursive(arr, length, largest);
printf("\n%d", z);
}
I followed your suggestions, using pointers instead of arrays, and probably the program looks way better. But still it is not doing it's not showing the maximum correctly. I think the logic is correct.
First thing pay attention to compiler warnings, your recursive function doesn't return value when you enter the else part.
Now the second thing is please don't use things like *(arr+n) which is hard to read instead use arr[n], also while just a preference when using arrays as function arguments use int arr[] to call the function instead of int *arr (in the first version it's clear you should pass an array).
Third thing is to name your things instead of int recursive describe what the function is doing for example int maxElemRecursive
So your recursive function should be something like
int maxElemRecursive(int arr[],int n,int largest)
{
if(n==0) return largest;
if(arr[n] > largest) // No need for else because return largest; would've returned value;
{
largest = arr[n];
}
return maxElemRecursive(arr,n-1,largest); // You have to return the value of the function.
// You still pass the array with just arr.
}
In C usually you can't declare an array whose size is unknown at compile-time, hence int v[n] is dangerous code.
Depending on your compiler and the compiler's settings this could be a compile error or it could be a bug.
For such problems you need to learn about pointers and dynamic memory allocation.
Side-note: After C99 there are stuff like Variable Length Arrays but the rules are a little advanced.
Also to pass an array to a function you give the array a pointer as an argument:
int z = recursion(v, n, v[0]);
instead of:
int z = recursion(v[n], n, v[0]);
I'm currently trying to pass an array of (values[3]) which it's first 3 values contain user input. However, I'm getting the error "expected int* but argument is type of int". I've tried to pass to method1, without the iteration of 'i', using the first three positions in the values array, but that's as far as I managed to attempt to fix it, any help would be much appreciated!
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
for(i=0;i<3;i++)
method1(values[i]);
}
int method1(int values[3])
{
}
You cannot pass an array to a function as an array - it "decays" to a pointer. There are two issues with your code:
There is no forward declaration of method1 visible at the point of invocation, and
You are passing values[i], a scalar value in place of an array.
A forward declaration is necessary because otherwise the compiler would assume that method1 takes an returns an int, which is not true. Add this line before main
int method1(int values[]);
You could also move method1 above main to fix this without providing a forward declaration. Also, 3 inside square brackets is not necessary, because the array is passed like a pointer anyway.
If you want to pass the entire array, pass values. Of course, i becomes unnecessary:
int res = method1(values);
#include <stdio.h>
int main(void)
{
int i;
int values[3];
printf("Enter three consecutive numbers (With spaces between)");
scanf("%d %d %d",&values[0],&values[1],&values[2]);
method1(values, 3);
getchar();
getchar();
return 0;
}
int method1(int* values, int size)
{
int i;
for(i=0; i<size; i++){
printf("%d ", values[i]);
}
return 1;
}
In C, arrays are passed by reference, you can see method1's first argument is int* that refers first element of array, and second argument is size of this array.
I'm getting a compile errors, that I can't really fix. I need to create a program that initializes an in array, then write a biggest function that takes 2 parameters, an array and it's length and returns the index of the largest element in the array. I will then call this function from main. Can anyone tell me what is the problem?
errors:part1.c: part1.c: In function 'main':
part1.c:6:3: warning: implicit declaration of function 'largest'
part1.c:7:23: error: expected expression before ']' token
part1.c: In function 'largest':
part1.c:17:4: warning: statement with no effect
Thanks!
#include <stdio.h>
int main()
{
int myArray[]={1,2,3,4,5,6};
largest(myArray,6);
printf("%d",myArray[]);
return 0;
}
int largest(int array[], int length)
{
length = sizeof(array)/sizeof(array[0]);
int i = 1;
int max = array[0];
for(i; i<length; i++)
{
if(max < array[i])
{
max = array[i];
}
}
return max;
}
ISSUE 1
You use largest() in main() before you define it. Use a prototype, or move the definition above main().
ISSUE 2
In:
length = sizeof(array)/sizeof(array[0]);
You declare length as int length, but assign to it something of type size_t. That caused the error error: 'length' redeclared as different kind of symbol in the original version of your question.
ISSUE 3
In
for(i; i<length; i++)
you do not assign a value to i. Did you mean
for(i=0; i<length; i++)
? Although you did previously assign a value to i, I believe this is causing warning: statement with no effect (though hard to be sure without line numbers in the provided code).
Also, arrays in C are 0-based. You probably want to initialize i to 0 rather than 1.
ISSUE 4
In the line
printf("%d",myArray[]);
you use %d as a formatting specifier, which means that the supplied argument is expected to be an integer value. You supply an array instead.
C compiles your code in one pass. This means that everything should be defined before it is used. Your function largest is defined after its use, therefore once the compiler sees
largest(myArray,6);
it still doesn't know that largest exists!
The solution would be to either move the definition of largest above main, or better, forward declare the function:
#include <stdio.h>
int largest(int array[], int length);
int main()
{
int myArray[]={1,2,3,4,5,6};
largest(myArray,6);
printf("%d",myArray[]);
return 0;
}
int largest(int array[], int length)
{
/* implementation of largest */
}
Also, the sizeof(array) will not give you the number of elements in largest because that information is lost upon function call. You could move that expression up in the function call to compute and pass the length parameter:
largest(myArray,sizeof(myArray)/sizeof(myArray[0]));
This may also be a typo, but you probably meant to store and print the maximum value:
int max = largest(myArray,sizeof(myArray)/sizeof(myArray[0]));
printf("%d\n",max);
Put a declaration of largest() before main() to resolve the implicit declaration warning:
int largest(int array*, int length);
int main()
The error error: expected expression before ']' token is caused by:
printf("%d",myArray[]);
To print the largest value, you need to store the result of largest() or use it as an argument to printf():
printf("%d", largest(myArray, 6));
This is not what you expect:
length = sizeof(array)/sizeof(array[0]);
as arrays decays to pointers when passed as arguments. It is equivalent to:
length = sizeof(int*)/sizeof(int);
Just use the length argument to control the iteration. Recommend make the arguments to largest() const as the function does not modify them.
The warning: statement with no effect is caused by the i; in the for:
for(i; i<length; i++)
change to:
for(; i<length; i++)
or:
for(i = 0; i<length; i++)
or if C99:
for(int i = 0; i<length; i++)
You could also just move the definition of largest() above the definition of main() and it would work.
Many people have pointed out many issues but surprised no one has mentioned this:
int largest(int array[], int length)
{
length = sizeof(array)/sizeof(array[0]);
Nope, sizeof does not do what you appear to think it does here. It does not magically know the size of your allocations, only takes the size of the underlying type. What you have done is equivalent to sizeof(int*)/sizeof(int).
You should trust the length parameter the caller gave you. There's no way to get the actual size of the array using sizeof, only let the caller tell you how big it is.
You have an error and warnings .. the error is clearly more important.
printf("%d",myArray[]);
the %d format specification implies you want to write an int value, this is not the case, and the likely cause of your error.
There are other warnings that deserved your attention, such as not providing a function prototype for your 'largest` function etc, but those are secondary to fixing the error that prevents compilation.
Of course the warnings should also be eliminated, or a conscious decision should be made to ignore them after examining them.
I have an int array and I need to find the number of elements in it. I know it has something to do with sizeof but I'm not sure how to use it exactly.
If you have your array in scope you can use sizeof to determine its size in bytes and use the division to calculate the number of elements:
#define NUM_OF_ELEMS 10
int arr[NUM_OF_ELEMS];
size_t NumberOfElements = sizeof(arr)/sizeof(arr[0]);
If you receive an array as a function argument or allocate an array in heap you can not determine its size using the sizeof. You'll have to store/pass the size information somehow to be able to use it:
void DoSomethingWithArray(int* arr, int NumOfElems)
{
for(int i = 0; i < NumOfElems; ++i) {
arr[i] = /*...*/
}
}
int a[20];
int length;
length = sizeof(a) / sizeof(int);
and you can use another way to make your code not be hard-coded to int
Say if you have an array array
you just need to:
int len = sizeof(array) / sizeof(array[0]);
I personally think that sizeof(a) / sizeof(*a) looks cleaner.
I also prefer to define it as a macro:
#define NUM(a) (sizeof(a) / sizeof(*a))
Then you can use it in for-loops, thusly:
for (i = 0; i < NUM(a); i++)
It is not possible to find the number of elements in an array unless it is a character array. Consider the below example:
int main()
{
int arr[100]={1,2,3,4,5};
int size = sizeof(arr)/sizeof(arr[0]);
printf("%d", size);
return 1;
}
The above value gives us value 100 even if the number of elements is five.
If it is a character array, you can search linearly for the null string at the end of the array and increase the counter as you go through.
In real we can't count how many elements are store in array
But you can find the array length or size using sizeof operator.
But why we can't find how many elements are present in my array.
Because when we initialise an array compiler give memory on our program like a[10] (10 blocks of 4 size) and every block has garbage value if we put some value in some index like a[0]=1,a[1]=2,a[3]=8; and other block has garbage value no one can tell which value is garbage and which value is not garbage that's a reason we cannot calculate how many elements in an array. I hope this will help you to understand. Little concept
Super easy.
Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof().
For example, given an integer array called myArray
int numArrElements = sizeof(myArray) / sizeof(int);
Now, if the data type of your array isn't constant and could possibly change, then make the divisor in the equation use the size of the first value as the size of the data type.
For example:
int numArrElements = sizeof(myArray) / sizeof(myArray[0]);
This way, the code is type agnostic and will function correctly no matter the data type of the array.
I used following code as suggested above to evaluate number of elements in my 2-dimensional array:
#include <stdio.h>
#include <string.h>
void main(void)
{
char strs[3][20] =
{
{"January"},
{"February"},
{""}
};
int arraysize = sizeof(strs)/sizeof(strs[0]);
for (int i = 0; i < arraysize; i++)
{
printf("Month %d is: %s\n", i, strs[i]);
}
}
It works nicely. As far as I know you can't mix up different data types in C arrays and also you should have the same size of all array elements (if I am right), therefore you can take advantage of that with this little trick:
count number of bytes with sizeof() function from whole 2d array (in this case 3*20 = 60 bytes)
count number of bytes with sizeof() function from first array element strs[0] (in this case 20 bytes)
divide whole size with size of one element what will give you number of elements
This snipped should be portable for 2d arrays in C however in other programming languages it could not work because you can use different data types within array with different sizes (like in JAVA).
The question is simple: given a C++ array (e.g. x as in int x[10]), how would you get the number of elements in it?
An obvious solution is the following macro (definition 1):
#define countof( array ) ( sizeof( array )/sizeof( array[0] ) )
I cannot say this isn’t correct, because it does give the right answer when you give it an array. However, the same expression gives you something bogus when you supply something that is not an array. For example, if you have
int * p;
then countof( p ) always give you 1 on a machine where an int pointer and an int have the same size (e.g. on a Win32 platform).
This macro also wrongfully accepts any object of a class that has a member function operator[]. For example, suppose you write
class IntArray {
private:
int * p;
size_t size;
public:
int & operator [] ( size_t i );
} x;
then sizeof( x ) will be the size of the x object, not the size of the buffer pointed to by x.p. Therefore you won’t get a correct answer by countof( x ).
So we conclude that definition 1 is not good because the compiler does not prevent you from misusing it. It fails to enforce that only an array can be passed in.
What is a better option?
Well, if we want the compiler to ensure that the parameter to countof is always an array, we have to find a context where only an array is allowed. The same context should reject any non-array expression.
Some beginners may try this (definition 2):
template <typename T, size_t N>
size_t countof( T array[N] )
{
return N;
}
They figure, this template function will accept an array of N elements and return N.
Unfortunately, this doesn’t compile because C++ treats an array parameter the same as a pointer parameter, i.e. the above definition is equivalent to:
template <typename T, size_t N>
size_t countof( T * array )
{
return N;
}
It now becomes obvious that the function body has no way of knowing what N is.
However, if a function expects an array reference, then the compiler does make sure that the size of the actual parameter matches the declaration. This means we can make definition 2 work with a minor modification (definition 3):
template <typename T, size_t N>
size_t countof( T (&array)[N] )
{
return N;
}
This countof works very well and you cannot fool it by giving it a pointer. However, it is a function, not a macro. This means you cannot use it where a compile time constant is expected. In particular, you cannot write something like:
int x[10];
int y[ 2*countof(x) ]; // twice as big as x
Can we do anything about it?
Someone (I don’t know who it is – I just saw it in a piece of code from an unknown author) came up with a clever idea: moving N from the body of the function to the return type (e.g. make the function return an array of N elements), then we can get the value of N without actually calling the function.
To be precise, we have to make the function return an array reference, as C++ does not allow you to return an array directly.
The implementation of this is:
template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define countof( array ) (sizeof( _ArraySizeHelper( array ) ))
Admittedly, the syntax looks awful. Indeed, some explanation is necessary.
First, the top-level stuff
char ( &_ArraySizeHelper( ... ))[N];
says _ArraySizeHelper is a function that returns a reference (note the &) to a char array of N elements.
Next, the function parameter is
T (&array)[N]
which is a reference to a T array of N elements.
Finally, countof is defined as the size of the result of the function _ArraySizeHelper. Note we don’t even need to define _ArraySizeHelper(), -- a declaration is enough.
With this new definition,
int x[10];
int y[ 2*countof(x) ]; // twice as big as x
becomes valid, just as we desire.
Am I happy now? Well, I think this definition is definitely better than the others we have visited, but it is still not quite what I want. For one thing, it doesn’t work with types defined inside a function. That’s because the template function _ArraySizeHelper expects a type that is accessible in the global scope.
I don’t have a better solution. If you know one, please let me know.
#include<stdio.h>
int main()
{
int arr[]={10,20,30,40,50,60};
int *p;
int count=0;
for(p=arr;p<&arr+1;p++)
count++;
printf("The no of elements in array=%d",count);
return 0;
}
OUTPUT=6
EXPLANATION
p is a pointer to a 1-D array, and in the loop for(p=arr,p<&arr+1;p++)
I made p point to the base address. Suppose its base address is 1000; if we increment p then it points to 1002 and so on. Now coming to the concept of &arr - It basically represents the whole array, and if we add 1 to the whole array i.e. &arr+1, it gives the address 1012 i.e. the address of next 1-D array (in our case the size of int is 2), so the condition becomes 1000<1012.
So, basically the condition becomes
for(p=1000;p<1012;p++)
And now let's check the condition and count the value
1st time p=1000 and p<1012 condition is true: enter in the loop, increment the value of count to 1.
2nd time p=1002 and p<1012 condition is true: enter in the loop, increment the value of count to 2.
...
6th time p=1010 and p<1012 condition is true: enter in the loop, increment the value of count to 6.
Last time p=1012 and p<1012 condition is false: print the value of count=6 in printf statement.
sizeof returns the size in bytes of it's argument. This is not what you want, but it can help.
Let's say you have an array:
int array[4];
If you apply sizeof to the array (sizeof(array)), it will return its size in bytes, which in this case is 4 * the size of an int, so a total of maybe 16 bytes (depending on your implementation).
If you apply sizeof to an element of the array (sizeof(array[0])), it will return its size in bytes, which in this case is the size of an int, so a total of maybe 4 bytes (depending on your implementation).
If you divide the first one by the second one, it will be: (4 * the size of an int) / (the size of an int) = 4; That's exactly what you wanted.
So this should do:
sizeof(array) / sizeof(array[0])
Now you would probably like to have a macro to encapsulate this logic and never have to think again how it should be done:
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
You need the parentheses enclosing all the macro as in any other complex macro, and also enclosing every variable, just to avoid unexpected bugs related to operators precedence.
Now you can use it on any array like this:
int array[6];
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(array);
/* nmemb == 6 */
Remember that arguments of functions declared as arrays are not really arrays, but pointers to the first element of the array, so this will NOT work on them:
void foo(int false_array[6])
{
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(false_array);
/* nmemb == sizeof(int *) / sizeof(int) */
/* (maybe ==2) */
}
But it can be used in functions if you pass a pointer to an array instead of just the array:
void bar(int (*arrptr)[7])
{
ptrdiff_t nmemb;
nmemb = ARRAY_SIZE(*arrptr);
/* nmemb == 7 */
}
void numel(int array1[100][100])
{
int count=0;
for(int i=0;i<100;i++)
{
for(int j=0;j<100;j++)
{
if(array1[i][j]!='\0')
{
count++;
//printf("\n%d-%d",array1[i][j],count);
}
else
break;
}
}
printf("Number of elements=%d",count);
}
int main()
{
int r,arr[100][100]={0},c;
printf("Enter the no. of rows: ");
scanf("%d",&r);
printf("\nEnter the no. of columns: ");
scanf("%d",&c);
printf("\nEnter the elements: ");
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
scanf("%d",&arr[i][j]);
}
}
numel(arr);
}
This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)
we can find number of elements in array only if array is declared in this format
int a[]={1,2,3,4,5,6};
number of element in array is
n=sizeof(a) / sizeof(a[0]);
we should no able to calculate array size if it is declared like this int a[10]={1,2,3,4,5,6}
i mostly found a easy way to execute the length of array inside a loop just like that
int array[] = {10, 20, 30, 40};
int i;
for (i = 0; i < array[i]; i++) {
printf("%d\n", array[i]);
}
If we don't know the number of elements in the array and when the input is given by the user at the run time. Then we can write the code as
C CODE:
while(scanf("%d",&array[count])==1) {
count++;
}
C++ CODE:
while(cin>>a[count]) {
count++;
}
Now the count will be having the count of number of array elements which are entered.
Assuming you have an array with elements 1,3,4.
To know its length, you'd need to use the sizeof function as follows:
int myArray[] = {1,3,4};
int len = sizeof(myArray) / sizeof(myArray[0]);
You can check the number of elements by printing the output as follows:
cout<<"This array has " << len << " elements";
The full program would be as follows:
#include <iostream>
using namespace std;
int main()
{
int myArray[] = {1,3,4};
int len = sizeof(myArray) / sizeof(myArray[0]);
cout<<"The array has " << len << "elements";
return 0;
}
Actually, there is no proper way to count the elements in a dynamic integer array. However, the sizeof command works properly in Linux, but it does not work properly in Windows. From a programmer's point of view, it is not recommended to use sizeof to take the number of elements in a dynamic array. We should keep track of the number of elements when making the array.
I'm trying to learn pointer in C and am writing this little integer array pointer exercise,but ran into a invalid application of sizeof to incomplete type int[] problem. Please tell me where did I go wrong and how to solve it. Thank you.
#include <stdio.h>
int intA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int intB[];
void int_copy(const int *source, int *destionation, int nbr)
{
int i;
for(i=0;i<nbr;i++)
{
*destionation++ = *source++;
}
}
int main()
{
int *ptrA = intA;
int *ptrB = intB;
int sizeA = sizeof(intA);
int nbrA = sizeof(intA)/sizeof(int);
printf("\n\n");
printf("[Debug]The size of intA is:%d\n", sizeA);
printf("[Debug]That means the number of elements is:%d\n", nbrA);
printf("\n\nThe values of intA are:\n");
int i;
for(i=0;i<nbrA;i++)
{
printf("[%d]->%d\n", i, intA[i]);
}
int_copy(ptrA, ptrB, nbrA);
int sizeB = sizeof(intB);
int nbrB = sizeof(intB)/sizeof(int);
printf("\n\n");
printf("[Debug]The size of intB is:%d\n", sizeB);
printf("[Debug]That means the number of elements is:%d\n", nbrB);
printf("\n\nThe values of intB are:\n");
for(i=0;i<nbrB;i++)
{
printf("[%d]->%d\n", i, *ptrB++);
}
}
# cc -g -o int_copy int_copy.c
int_copy.c: In function 'main':
int_copy.c:36: error: invalid application of 'sizeof' to incomplete type 'int[]'
int_copy.c:37: error: invalid application of 'sizeof' to incomplete type 'int[]'
The strange thing that I observed is when I ran gdb, I monitored that the copy function, int_copy, runs for 9 times which seems to be right, but the print of intB after the copy function only displays one item in that array.
I'm still struggling about pointers now, so please do help me and forgive my ignorance. Thank you very much.
intB is basically a pointer, and sizeof on it will yield the same as sizeof on int, that's why the print appears only once.
intA is an array with a known size, so the sizeof works.
You need to remember that sizeof is not a run-time call, although it may look so syntactically. It's a built-in operator that returns the size of the type in bytes at the compilation time, and at the compilation time intB is a pointer that should later point to a newly allocated array.
You are also in trouble here, because IntB doesn't have a size so int_copy really doesn't work for it. There is nowhere to copy the ints!
When declaring an array, you have to either give the size inside [] or use an initializer with the values, so the compiler can count them and figure out the size itself.
Actually your int intB[]; statement is invalid, which compiler are you using?
Also, beware that arrays and pointers are not really the same. You can however use the array handle in a call to a function that expects a pointer, so you can give intA to your int_copy function without copying it to a pointer. http://www.lysator.liu.se/c/c-faq/c-2.html