POINTER\ARRAY CONFUSION

plz tell me the error!!!! it doesn't work properly.

#include <iostream>
using namespace std;
int main()
{
int *num;

num[4]=6;
*(num+3)=7;
cout<<num[3]<<num[4];
return 0;
}
I would be greatly thankful if you also remove my confusion about
1. does num[4]=6 mean num[0] to num[4]
2. does *(num+3) mean num[4] or num[3].


\\however, if i change 3 with 2 than it does work.
#include <iostream>
using namespace std;
int main()
{
int *num;

num[4]=6;
*(num+2)=7;
cout<<num[2]<<num[4];

return 0;
}
THANK YOU!


closed account (iLUjLyTq)
You need to allocate memory with your pointer for an array before you can use it.

int *num = new int[10];

num[4] = 6;
means you assign value of 6 to array element 4

Also *(num+2) is another way of typing num[2].

Don't forget to free memory with delete before return statement:

delete [] num;
Last edited on
if you want to use an array, you should declare an array.

it is true that "array names are constant pointers to the first element of the array". which means, when you type;

int * num;

you actually creating a pointer to one and only ONE int type memory location. it's not an array. although, it will act as an array. so if you do;

num[4] = 6;

it will "work" with no guarantee. the problem with this code above, is you do not know what do you have on the location num[4]

so it's dangerous, you're messing with the stack.

what you should do;

int num[10];

this code allocates 10 memory locations starting with 0. so you have num[0], num[1]....num[9], in total, 10 locations. then, if you like, you can do pointer arithmetic as you did on your code.

you should read a chapter about arrays from a C++ book.
I can recommend you "Sams teachyourself C++ in 21 days", or "C++ complete reference" or any other C++ book. also CPlusPlus tutorial of this site.
Last edited on
Topic archived. No new replies allowed.