I was trying to initialize an array in C and for each element GCC is generating a mov instruction(which is an inefficient approach if there are many elements to be initialized). How will I load memory with array data and return a pointer from it instead of initializing this way ?
6:array.c **** int a[]={1,2,3,4,5,9};
26 .loc 1 6 0
27 0008 C745E001 movl $1, -32(%rbp)
27 000000
28 000f C745E402 movl $2, -28(%rbp)
28 000000
29 0016 C745E803 movl $3, -24(%rbp)
29 000000
30 001d C745EC04 movl $4, -20(%rbp)
30 000000
31 0024 C745F005 movl $5, -16(%rbp)
31 000000
32 002b C745F409 movl $9, -12(%rbp)
32 000000
I believe the following answers your question “How will I load memory with array data and return a pointer from it instead?”:
This compiles to:
As you can see, the values live on the data segment, and
main()simply takes a pointer to the data.Of course, if you mutate
a[], these mutations will still be there next time you take the address ofa_data. If you expect to get the original values, you should be making a copy ofa_data, not simply using a pointer to it.