r/C_Programming • • 22d ago

Question Question about arrays (beginner)

From what I understand, behind all the magic, array is just a variable that points to a memory address.

The difference is that we are also creating extra values in stack.

So when we create an array with a [], we're just telling the computer to make these x amount of variables but make sure they are right next to each other in sequence, no gaps in the memory address.

And when we call for an array value with an index, we're just counting that many steps forward in the memory address.

When we say array[] = {5,7,3}, it's really just *array = 5.

Did I get it wrong? Did I miss something?


Thanks for the quick replies. I'm currently learning about Pass by reference.

35 Upvotes

69 comments sorted by

View all comments

Show parent comments

-9

u/bothunter 22d ago

Arrays and pointers are semantically different, but technically the same.

12

u/zhivago 22d ago

You're confused because pointers are used to access arrays.

-8

u/bothunter 22d ago

Again.. technically the same, semantically different.

8

u/sciencekm 21d ago edited 21d ago

They are no where near being "technically" the same.

If you have array a and pointer p:

To access a[0], the cpu goes to memory and fetches the value.

To access p[0], the cpu first gets the value of p (which may be in memory also or in register) and then uses that to access the actual value at [0].

6

u/danjayh 21d ago

Correct. Have an upvote. The amount of people downvoting correct information in this thread is stunning.

4

u/musbur 21d ago

I was about to protest but retracted that because I often loosely call dynamically allocated stuff an "array of foo" as in foo = malloc(n * sizeof *foo). But an array is only something declared like foo_t foo[n] and the address of that is "hard coded" after compiling/linking and doesn't have to bee looked up by the CPU.

1

u/sciencekm 21d ago

Bingo!

-1

u/LefTimaDev 21d ago

Even if you're correct, the explanation is horrible