Changing array inside function in C

前端 未结 7 1948
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 08:40

I am learning C and confused why a array created in the main wont change inside the function, i am assuming the array passed is a pointer, and changing the pointer should\'v

相关标签:
7条回答
  • 2020-12-01 09:25

    so when you pass the array you get the address of it's beginning:

    memory address

    |-junk-| 1000

    |---0---| 1008 <- start of your array

    |---10--| 1012

    . . . .

    when you get the pointer in your function its value is 1008(example) so changing that will only mean you now point to another place. that is not what you want. you can change the integers pointed at directly via the * operator, so *array = 99; will change the first element, *(array+1) = 98; the second and so on. you can also, more naturally use the [] operator. so in your function array[0] = 99; will actually change the original array.

    0 讨论(0)
提交回复
热议问题