Thread: confused with array and pointers

  1. #1
    Registered User
    Join Date
    Jan 2022
    Posts
    3

    confused with array and pointers

    Hi
    I don't understand why I'm getting wrong result of the following code:
    Code:
    #include <stdio.h>
    int main(void) {
      int myarray[5] = {10,20,30,40,50};
      int *p = myarray;
      printf("pointer points to third element from myarray: %d\n", p[2]);
      printf("for convenience print the whole arryy:");
      for (int i=0; i<5; i++) {
        printf(" %d", myarray[i]);
      }
      printf("\n");
      /* if we want to change value of a certain address position we do:*/
      p = &myarray[0]; /* get the address of the first array element */
      *p = 11; /* change its value */
      p = &myarray[4]; /* get the address of the fifth array element */
      *p = 55; /* change its value */
      printf("After the changes:");
      for (int i=0; i<5; i++) {
        printf(" %d", p[i]);
      }
      printf("\n");
      return 0;
    }
    my result:

    pointer points to third element from myarray: 30
    for convenience print the whole arryy: 10 20 30 40 50
    After the changes: 55 32766 -59239168 -176176675 0

    expected result:
    pointer points to third element from myarray: 30
    for convenience print the whole arryy: 10 20 30 40 50
    After the changes: 11 20 30 40 55

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Take a look at line 18

  3. #3
    Registered User
    Join Date
    Jan 2022
    Posts
    3
    wow that was fast, many thanks but sorry I don't understand it, obviously I'm confusing something from the pointers lesson.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    p no longer points to the start of your array.

    So you print the tail end of the array, then whatever 'garbage' there is in memory.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Jan 2022
    Posts
    3
    super cool, that is logical now as well.
    Thanks Salem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Arrays and pointers, confused.
    By jjohan in forum C Programming
    Replies: 5
    Last Post: 09-25-2014, 12:22 PM
  2. Confused about Pointers
    By JoshD75 in forum C Programming
    Replies: 7
    Last Post: 03-28-2011, 09:43 PM
  3. Still confused with pointers
    By desmond5 in forum C Programming
    Replies: 8
    Last Post: 02-23-2008, 09:32 PM
  4. confused with pointers
    By Mahdi123 in forum C Programming
    Replies: 2
    Last Post: 04-25-2007, 01:08 PM
  5. Very confused with pointers
    By killerasp in forum C++ Programming
    Replies: 5
    Last Post: 01-30-2002, 06:44 PM

Tags for this Thread