Quiz! Easy but Tricky for programmers, What you Think?

Hi Guys
Today I had an Quiz and by accident my Lecture base 3 of the questions on the following concept::

1
2
int a[10];
int *p=a;


and as you might know:

 
a=&a[0]


What do you think? Is that true or false declaration??
closed account (3TXyhbRD)
True
But I have a problem regarding this... p is a pointer and can point to a integer value but according to

a=&a[0]

we are assigning it to an address of a value...In my idea it must be int *p=a; or we must say p=a not *p Am I right?
Last edited on
closed account (S6k9GNh0)
According to the GCC compiler, they are the same thing: http://codepad.org/n2HkK2JN

assert will give output on false conditions, therefor the conditions in the example is true.
However, please note that c-arrays and pointers are NOT treated the same. Please beware as it can be confusing.
Last edited on
closed account (3TXyhbRD)
But I have a problem regarding this... p is a pointer and can point to a integer value but according to

a=&a[0]

we are assigning it to an address of a value...In my idea it must be int *p=a; or we must say p=a not *p Am I right?


1
2
int a[10], *p;
p = a;

Is that what you mean? If yes, that is true.

However this isn't true:
1
2
int a[10];
int p = a;

a without any [] is a pointer to an int array as you may know and in this case, p is declared as an int not as a pointer to an int type.

Some more information that you may know about arrays:

1
2
int a[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout<<a[3]<<'='<<*(a+3);
The above code will list the same element of the array using two different methods.

1
2
3
4
5
6
7
int a[10]={1,2,3,4,5,6,7,8,9,10};

for (int i=0; i<10; i++)
    cout<<a[i]<<' ';
cout<<endl;
for (int i=0; i<10; i++)
    cout<<i[a]<<' ';
Will the code above give compiling errors? If it doesn't what will be displayed and if it does which is the error?
However this isn't true:

int a[10];
int p = a;


I know that this is not true and>>

1
2
int a[10], *p;
p = a;


This is true...My question is that >>

1
2
int a[10], *p;
*p = a;


Here *p means the content of where p points at...Can we put an address of a[0] inside p or can we say

*p=&a[0]






closed account (3TXyhbRD)
a[0] is not a pointer, is a value.
1
2
3
4
5
6
int a[10], *p;

//The following do the same
*p = a;
*p = &a[0];
//And it attributes the address where <a[0]> is not the value <a[0]> has. 
The variable "a" is an array, but it degenerates into a pointer to the first element of the array when used as a pointer.

Hence, the answer to the original question is false.


[edit]
I just noticed that the original premise used the assignment operator (a=&a[0]) and not the equality-comparison operator (a==&a[0]). Was this intentional? Because my response was based upon the comparison. The assignment is illegal and should not compile.
Last edited on
Topic archived. No new replies allowed.