Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning constants at Run Time in pointers

Status
Not open for further replies.

vsp78

Programmer
Dec 24, 2002
1
US
I am curious to know,whether it is possible to assign array of constants at once at runtime using pointers.
for ex.

FIGURE-1
======================
int *x;
x = (int *) malloc(3 * sizeof(int));
*x= {7,8,2};
printf("first element of array x is %d\n",x[0]);

===========================
results in an error.

I know i can overcome this problem if I do:-

FIGURE-2
=======================================
int *x;
int y[]={7,8,2};
x = (int *) malloc(3 * sizeof(int));
x=y;
printf("first element of array x is %d\n",x[0]);
=======================================
works perfectly fine.

I just want to know when the compiler knows that x has been allocated the size for 3 integers, why does it give error in FIGURE-1 ? Is there any other statement which can be used in place for 3rd statement in FIGURE-1?

thanx.



 
The array initializer syntax fails because it can only be used at initialization. That's why it works for y in the second example, but not for x in the first. There's no equivalent statement that can be used after initialization, but there are many other ways to fill up the array after you've made it, with for loops being a common one.
 
Hi,

Note the short program below.

#include <stdio.h>
#include <conio.h>

int main(void)
{
int *x;
int y[] = {7,8,9};

// First part
x = y;
printf(&quot;\n%d %d %d&quot;,x[0], x[1],x[2]);

// Second part
printf(&quot;\n%d &quot;,*x);
++x;
printf(&quot;\n%d &quot;,*x);
++x;
printf(&quot;\n%d &quot;,*x);

getch();
return 0;
}


You don't have to malloc for the pointer. It is just a pointer that doesn't care where it points to as long as it points to an int. The second part of the program is an example of pointer arithmetic. Pointer arithmetic is why an int pointer should point to an int.

The space for &quot;7, 8, 9&quot; is already allocated with the line
int y[] = (7, 8, 9);

the name of an array(ie. y) is like a pointer and the line
x = y;
just makes a real pointer point to where array pointer points to.

Hope this helps.





Pappy
You learn something new everyday.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top