#include<stdio.h>
int main() {
int buff[] = {1,2,3,4,5,6,9,10};
char c = (buff+1)[5];
printf("%d\n",c);//output is 9
return 0;
}
Can someone explain it clearly how this is happening and why
Recall:
In C the square braces [ ] are implicitly *( ... ).
What is going on in the snippet of code you provided is not obvious pointer arithmetic. This line:
char c = (buff+1)[5];
... is equivalent to the following (by the C standard):
char c = *( ( buff + 1 ) + 5 );
... which points to the 7th element in the array (6th position) and dereferences it. It should output 9, not 19.
Remark:
Following the note about square braces, it's important to see that the following is equivalent.
arr[ n ] <=> n[ arr ]
... where arr is an array and n is a numerical value. A more complicated example:
' '[ "]; i < 0; i++; while ( 1 ); do something awesome (y)." ];
... of entirely valid pointer arithmetic.
{1, 2, 3, 4, 5, 6, 9, 10};
| |
buff buff+1 = {2, 3, 4, 5, 6, 9, 10} (say buff_1)
|
buff_1[5] = 9
Related
I tried this code..As you can see the problem is the empty elements are zero. So, I tried to check with it but the thing is I can have 0 as an element.
int main()
{
int array[10] = {1, 2, 0, 3, 4};
printf("%d\n", sizeof(array)/ sizeof(*array)); // This is the size of array
int i = 0;
while(array[i] != 0 && i < 10) {
i++;
};
printf("%d\n", i);
return 0;
}```
You can't. int array[10] will always create an array of 10 elements and you can't ask the compiler which of them have been assigned.
What you could do is int array[] = {1, 2, 0, 3, 4} then the compiler will infer the number of elements for you and you'll have sizeof(array)/ sizeof(*array) == 5
First set the array to a number outside the range of your inputs. Like a negative number.
for(i = 0;i < 10;i++)
array[i] = -1;
or set it to INT_MAX or INT_MIN
int array[10] = {1 , 2, 0, 3} . How can I find out that there are 4 elements here?
How can you say there are 4 elements there as you declared that int array[10] with the size of 10 elements. This implies, you already know the no. of elements. Also, in this scenario, you can't use an if statement to determine the no. of elements as you probably know that in C, if you initialize an array of 10 elements with less than 10 values, rest of them will automatically be assigned to 0.
You have several options:
You know how many elements are in the initializer, so you create another variable that stores that number:int array[10] = {1, 2, 0, 3, 4};
int num_items = 5;
You'll need to update num_items as you "add" or "remove" items to the array. If you treat the array as a stack (only add or remove at the highest index), then this is easy-ish:array[num_items++] = 7; // adds 7 after 4
...
x = array[--num_items]; // x gets 7, 7 is "removed" from the array, need special
// case logic for element 0
You pick a value that isn't valid (say -1) and initialize the remaining elements explicitly:int array[10] = {1, 2, 0, 3, 4, -1, -1, -1, -1, -1 };
You size the array for the initializer, meaning it can only ever store that many elements:int array[] = {1, 2, 0, 3, 4};
Otherwise, you'll need to use a different data structure (such as a linked list) if you need a container that can grow or shrink as items are added or removed.
I can't understand how the following elements are getting determined:
*(arr+1)[1] - 7 is printed.
**(arr+1) - 4 is printed.
#include <stdio.h>
int main()
{
int arr[3][3]={1,2,3,4,5,6,7,8,9};
printf("%d %d",*(arr+1)[1],**(arr+1));
return 0;
}
By definition, a[b] is equivalent to *(a + b).
[] (postfix) has higher precedence than * (prefix), so *a[b] parses as *(a[b]).
*(arr+1)[1] parses as *((arr+1)[1]).
*((arr+1)[1]) is equivalent to *(*(arr+1+1)).
*(*(arr+1+1)) reduces to **(arr+2).
**(arr+2) is equivalent to *(arr[2]).
*(arr[2]) is equivalent to *(arr[2]+0).
*(arr[2]+0) is equivalent to arr[2][0].
**(arr+1) is equivalent to *(arr[1]).
*(arr[1]) is equivalent to *(arr[1]+0).
*(arr[1]+0) is equivalent to arr[1][0].
As for the actual data:
int arr[3][3]={1,2,3,4,5,6,7,8,9};
is a bit hard to read. Better:
int arr[3][3]={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
In the first case, arr[2][0] gives you the first element (7) of the third subarray (7,8,9) while in the second case, arr[1][0] gives you the first element (4) of the second subarray (4,5,6).
arr can be more intuitively written like this:
int arr[3][3]={
{1,2,3},
{4,5,6},
{7,8,9},
};
*(arr+1)[1] is equivalent to **(arr+2) because a[n] is equivalent to *(a+n). arr+2 skips two rows, giving a pointer to {{7,8,9}}, then the two stars dereference the first of those values.
**(arr+1) works the same way.
I am still learning C but when I try and use a 2d array I get the errors:
/Users/harry/Dropbox/C/Practise/test_1/main.c:157:9: error: expected expression
int[,] numberGrid = {
^
/Users/harry/Dropbox/C/Practise/test_1/main.c:158:9: warning: too many braces
around scalar initializer [-Wmany-braces-around-scalar-init]
{1, 2, 3 },
My code is:
int main() {
int[,] numberGrid = {
{1, 2, 3 },
{4, 5, 6 },
{7, 8, 9 }
};
printf("%d\n", numberGrid[1, 1]);
}
As noted in the comments, the notation int[,] numberGrid = { … notation simply isn't C.
If you wrote either:
int numberGrid[3][3] = {
{1, 2, 3 },
{4, 5, 6 },
{7, 8, 9 }
};
or:
int numberGrid[][3] = {
{1, 2, 3 },
{4, 5, 6 },
{7, 8, 9 }
};
you would be able to get the array initializer to compile.
Then you need to fix the printf() to print an array element. The comma is no use in subscripts in C (for most practical purposes, it 'never' appears in a subscript — you can invent exceptions if you try hard enough, but you shouldn't write such code normally).
You could write:
printf("%d\n", numberGrid[1][1]);
to print 5. As written (printf("%d\n", numberGrid[1,1]);), you are printing an address as a signed decimal integer, which is not guaranteed to work well (data truncation on a 64-bit machine, etc).
Is it possible to create a subscripted array in C which uses another array as its indexes. I went through a link: IDL — Using Arrays as Subscripts
Arrays can be used as subscripts to other arrays. Each element in the subscript array selects an element in the subscripted array.
For another example, consider the statements:
A = [6, 5, 1, 8, 4, 3]
B = [0, 2, 4, 1]
C = A[B]
PRINT, C
This produces the following output:
6 1 4 5
Is the above possible in C programming.
Arrays can be used as subscripts to other arrays. Each element in the subscript array selects an element in the subscripted array.
Syntactically this is not directly possible in C. You've to use a loop to achieve this.
int a[] = {6, 5, 1, 8, 4, 3};
int b[] = {0, 2, 4, 1};
for (int i = 0; i < (sizeof(b)/sizeof(b[0])); ++i)
printf("%d\n", a[b[i]]);
If you really want it to look that neat, then wrap it in a function and you should be alright:
// returns the no. of elements printed
// returns -1 when index is out of bounds
int print_array(int *a, int *b, size_t na, size_t nb)
{
int i = 0;
for (i = 0; i < nb; ++i)
{
int const index = b[i];
if (index >= na)
return -1;
print("%d\n", a[index]);
}
return i;
}
The array index operator in C can only take integer arguments. This is because the compiler will expand the operation, like A[0], into a basic addition and dereference. As such, you can't pass an array as the operand to extract several indices from the original array.
Remember that A[0] is the same as *A, and A[1] is the same as *(A + 1), etc.
Yes ofcourse it is:
int a[6] = { 6, 5, 1, 8, 4, 3 };
int b[4] = { 0, 2, 4, 1 };
printf("\na[b[0]]=%d", a[b[0]]);
printf("\na[b[1]]=%d", a[b[1]]);
printf("\na[b[2]]=%d", a[b[2]]);
printf("\na[b[3]]=%d", a[b[3]]);
output:
a[b[0]]=6
a[b[1]]=1
a[b[2]]=4
a[b[3]]=5
No, that's not possible!
In C, the array operator [x] is just a shorthand for a pointer addition.
So a[x] is the same as (a+x)*
This means the only valid arguments for the array operator are Integers.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following code is an algorithm for searching for the maximum occurrence of an element in an array. This solution assumes that an element ranges from 0 to n-1.
void MaxRepetitions( int A[], int n ) {
int i=0; max=0, maxIndex;
for(i=0, i<n, i++)
A[A[i]%n] +=n;
for( i=0, i<n, i++)
if (A[i]/n > max) {
max = A[i]/n;
maxIndex=i;
}
return maxIndex;
}
How is A[A[i]%n] +=n; expanded?
Is A[A[i]%n] = A[A[i]%n] + n correct?
--
Edit
For the example where A = [2, 4, 7, 5, 4, 11], where n=6
A[0]%n = 2
A[1]%n = 4
A[2]%n = 1
A[3]%n = 5
A[4]%n = 4
A[5]%n = 5
After this loop:
for(i=0, i<n, i++)
A[A[i]%n] = A[A[i]%n] + n;
Iteration 1:
A[A[0]%n] = A[A[0]%n] + 6 --> A[2] = A[2] + 6 --> A[2] = 13
The array is now: A = [2, 4, 13, 5, 4, 11]
Iteration 2:
A[A[1]%n] = A[A[1]%n] + 6 --> A[4] = A[4] + 6 --> A[4] = 10
The array is now: A = [2, 4, 13, 5, 10, 11]
Iteration 3:
A[A[2]%n] = A[A[2]%n] + 6 --> A[1] = A[1] + 6 --> A[1] = 10
The array is now: A = [2, 10, 13, 5, 10, 11]
Iteration 4:
A[A[3]%n] = A[A[3]%n] + 6 --> A[5] = A[5] + 6 --> A[5] = 17
The array is now: A = [2, 10, 13, 5, 10, 17]
Iteration 5:
A[4] now is 10
A[A[4]%n] = A[A[4]%n] + 6 --> A[4] = A[4] + 6 --> A[4] = 16
The array is now: A = [2, 10, 13, 5, 16, 17]
Iteration 6:
A[5] now is 17
A[A[5]%n] = A[A[5]%n] + 6 --> A[5] = A[5] + 6 --> A[5] = 23
The array is now: A = [2, 10, 13, 5, 16, 23]
Now, once the second loop runs, A[i]/n for each of the elements is: A [0, 1, 2, 0, 2, 3 ]
It looks like this algorithm will choose 11 as the element with most occurrences which isn't true. Any help?
As others have said, <anything> += <value> is equivalent to <anything> = <anything> + <value> except that <anything> is evaluated only once.
Your analysis of the running of the algorithm is correct, but the problem is that the input violates the stated constraint that all elements are between 0 and n-1. In effect, since 11 % 6 = 5, the answer produced by the algorithm isn't completely wrong (modulo 6, the value 5 occurs the same number of times as the value 4). However, there is a further problem in that because the input constraint is violated, the counts are off for reasons that I explain in a comment below.
The best way to understand how this works is to look at another algorithm which, while seemingly quite different, is actually the same thing. This other algorithm is:
Allocate a separate array C[n]. (C for "count".)
Loop through each element A[i] of A and set C[A[i]] += 1. It's not too hard to see that, since each A[i] is between 0 and n-1, when this step finishes, C[j] for any j will be the number of times that the value j occurs among all the A[i].
Thus, the position of the largest element of C is the most frequently occurring value in A (with ties being resolved arbitrarily). Simply loop through C to find where this occurs and return the result.
Now the algorithm you posted is exactly that, but cleverly making use of two facts, both of which rely on the original values of A[i] being between 0 and n-1:
The value of A[i]%n will be exactly equal to the original value of A[i] regardless of how many times n has been added to A[i].
The value of A[i]/n will be exactly equal to the number of times n has been added to A[i], regardless of the original value of A[i].
So if we modify the second algorithm by adding n instead of 1, and by using %n and /n as is done in your posted algorithm, we can make A serve for both holding the original values and for holding the counts.
This:
A[A[i]%n] +=n
Is expanded to be equivalent to this:
A[A[i]%n] = A[A[i]%n] + n
Except that side-effects are only evaluated once. In other words, if the left expression had employed operators with side-effects like ++ and --, then these side-effects would only occur once, contrary to what had happened if you had actually written out the whole x = x + y expression, where side-effects in x would be evaluated twice.
A[A[i]%n] +=n
A[i] : value contained in array A at position i
A[i]%n : remainder of dividing this value by n (used to not allow this index go beyond the size of A
A[A[i]%n] : the value contained in that new position
A[A[i]%n] += n : add n to this value
Numerical example :
A[3] = {7, 10, 24}
n = 3
i = 0
A[A[0]%3] = A[7%3] // 7 = 2*3 + 1
= A[1]
= 10
add 3 ==> A[1] = 13
i = 1
A[A[1]%3] = A[13%3] // 13 = 4*3 +1
= A[1]
= 13
add 3 ==> A[1] = 16
i = 2
A[A[2]%3] = A[24%3] // 24 = 8*3 + 0
= A[1]
= 7
add 3 ==> A[1] = 10