Thread: Trouble accessing array

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    13

    Trouble accessing array

    I am writing my own code for malloc, calloc, and realloc.

    When using call I call:

    int *ptr = calloc(100, 4);

    But when I try to print the addresses using:

    for(i=0; i < 100; i++)
    fprintf(stderr,"0x%x\n", ptr[i]);

    Gives me all:
    0x0

    But using:
    for(i=0; i < 100; i++)
    fprintf(stderr,"0x%x\n", (ptr+i));

    I get all sequential addresses.

    Thoughts or ideas? I'm sure my malloc code works.

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    ptr[i] is not equivalent to (ptr+i). It's equivalent to *(p+i). Try doing *(p+i) in your second for loop there and you'll get a bunch of 0's like in your first test. If you want print the sequential addresses like you get with (p+i) try printing &p[i].

    Note: By sequential I'm assuming you actually mean they're sizeof(int) bytes apart. Unless you change ptr from being int *.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    13
    I actually have no idea what I was thinking when I posted that. Thanks for pointing out my mistake. It works now!

  4. #4
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    You can also use
    Code:
    fprintf(stderr,"%#x\n",
    instead.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. accessing outside of an array?
    By avaldi in forum C++ Programming
    Replies: 7
    Last Post: 07-09-2008, 03:01 AM
  2. accessing an array of structures
    By creative in forum C Programming
    Replies: 4
    Last Post: 12-27-2007, 12:52 PM
  3. Reversing character array without accessing thro' index.
    By Roaring_Tiger in forum C Programming
    Replies: 8
    Last Post: 08-28-2004, 10:52 AM
  4. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  5. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM