-
March 19th, 2009, 09:12 AM
#1
pointer question
Hello!
I got one code:
Code:
int main()
{
int *test1,a;
test1=&a;
test1[0]=5;
cout<<test1<<endl;
system("PAUSE");
return 0;
}
How is possible that compiler lets me use array test1[0] or something even if the test1 is pointer?
-
March 19th, 2009, 09:17 AM
#2
Re: pointer question
Arrays are just a special case of pointers, that's why.
test1[0] is simply another way of writing *(test1 + 0).
-
March 19th, 2009, 10:37 AM
#3
Re: pointer question
Thanks for the reply.
But what if I write
test[1]=5;
and
cout<<*(test1+1)<<endl;
the program crashes. What's the problem?
-
March 19th, 2009, 10:40 AM
#4
Re: pointer question
Originally Posted by StGuru
Thanks for the reply.
But what if I write
test[1]=5;
and
cout<<*(test1+1)<<endl;
the program crashes. What's the problem?
test1 points to an int. One and only one int. test1 is valid as it points to a. test1 + 1 isn't.
-
March 19th, 2009, 12:55 PM
#5
Re: pointer question
So if I put a[5], then it would work right?
-
March 19th, 2009, 12:58 PM
#6
Re: pointer question
Originally Posted by StGuru
So if I put a[5], then it would work right?
a is neither a pointer nor an array, but an int.
-
March 19th, 2009, 01:24 PM
#7
Re: pointer question
Originally Posted by laserlight
a is neither a pointer nor an array, but an int.
I think he means if he declared it as an array like
int a[5].
-
March 19th, 2009, 01:24 PM
#8
Re: pointer question
Originally Posted by StGuru
So if I put a[5], then it would work right?
Almost. In that case, a becomes a pointer, so you'd have
int a[5];
int* test = a;
You don't need a separate pointer though.
-
March 20th, 2009, 01:27 PM
#9
Re: pointer question
Yes, your right. :-)
I got one task where it was test= new int[5];
-
March 20th, 2009, 01:56 PM
#10
Re: pointer question
If you do that, don't forget to delete[] that memory when you're done with it.
-
March 20th, 2009, 02:10 PM
#11
Re: pointer question
Personally I wouldn't use new if there is a low volume of POD or plain old data involved. Just makes life easier.
ahoodin
To keep the plot moving, that's why.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|