how to initialize a value to pointer ?
-
i tried adding values to different addresses of arrays by using pointer but it doesn't work.
#include
int main()
{
int i, num[10];
int *p;
p = &num[0];for(i=0; i<=10; i++) { (p+i) = i; printf("\\n%d", \*(p+i)); } return 0;
}
-
Inside your for loop it needs to have this :
*(p+i) = i;
(p+i) is a pointer incremented by i. You have to dereference the pointer to save a value to where it is aiming.
if p = address of the num[0] then (p+i) is the address of the ith address and it is where i want to store the value, *(p+i) will give the value at that address i.e. de-referencing, below is the code i tried.
#include
int main()
{
int i, num[10];
int *p;
p = &num[0];for(i=0; i<=10; i++) { \*(p+i) = i; } for(i=0; i<=10; i++) { printf("\\n%d", \*(p+i)); } return 0;
}
-
if p = address of the num[0] then (p+i) is the address of the ith address and it is where i want to store the value, *(p+i) will give the value at that address i.e. de-referencing, below is the code i tried.
#include
int main()
{
int i, num[10];
int *p;
p = &num[0];for(i=0; i<=10; i++) { \*(p+i) = i; } for(i=0; i<=10; i++) { printf("\\n%d", \*(p+i)); } return 0;
}
You are very close. The problem now is your for loops are exceeding the capacity of num. It has 10 elements and your loops go from 0 to 10 inclusively. That is 11 elements - there is no num[11] item so that is a very bad thing. I don't like literal values so I made the number a const and adjusted the loops :
const int Count = 10;
void main()
{
int i;
int num[Count];
int *p;p = &num\[0\]; for( i=0; i < Count; i++ ) { \*(p+i) = i; } for( i=0; i < Count; i++ ) { trace( \_T( "item %d is %d" ), i, \*(p+i) ); } return 0;
}
Your code looks quite a bit like C but this is a section for ATL/WTL/STL is about C++. If you are actually using C then this code won't compile. You can make Count a macro definition and then it will.
-
i tried adding values to different addresses of arrays by using pointer but it doesn't work.
#include
int main()
{
int i, num[10];
int *p;
p = &num[0];for(i=0; i<=10; i++) { (p+i) = i; printf("\\n%d", \*(p+i)); } return 0;
}
-
You are very close. The problem now is your for loops are exceeding the capacity of num. It has 10 elements and your loops go from 0 to 10 inclusively. That is 11 elements - there is no num[11] item so that is a very bad thing. I don't like literal values so I made the number a const and adjusted the loops :
const int Count = 10;
void main()
{
int i;
int num[Count];
int *p;p = &num\[0\]; for( i=0; i < Count; i++ ) { \*(p+i) = i; } for( i=0; i < Count; i++ ) { trace( \_T( "item %d is %d" ), i, \*(p+i) ); } return 0;
}
Your code looks quite a bit like C but this is a section for ATL/WTL/STL is about C++. If you are actually using C then this code won't compile. You can make Count a macro definition and then it will.