4 Replies - 628 Views - Last Post: 22 March 2013 - 12:30 AM Rate Topic: -----

#1 Ajgilzean  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 27-July 10

Array offsets and Pointers

Posted 20 March 2013 - 12:03 AM

Say I have an array of integers called arrayOfInts declared as follows,
int *arrayOfInts = (int *)malloc(sizeof(int)*100);
// ... initialize the array with input



What I'm trying to do is make another pointer that can point to specific locations in arrayOfInts. Say for example I want to offset the array by 5 elements (to point to the 5th integer).
int *localArrayOfInts = arrayOfInts + 5;



Seems like this should work to me from basic pointer arithmetic but it's not working for me. Is there anything wrong with this?

Is This A Good Question/Topic? 0
  • +

Replies To: Array offsets and Pointers

#2 Adak  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 331
  • View blog
  • Posts: 1,168
  • Joined: 01-April 11

Re: Array offsets and Pointers

Posted 20 March 2013 - 01:25 AM

In C, if you cast the pointer that malloc() returns (you generally should never do that), and forget to include stdlib.h, and don't check the malloc() result for errors....

You'll wind up scratching your head rather badly, trying to figure out WTF??

Sound like you?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
   int *num=malloc(100*sizeof(int));
   int i;

   for(i=0;i<100;i++) {
      num[i]=i;
      printf(" %4d   ",num[i]);
   }
   return 0;
}


This post has been edited by Adak: 20 March 2013 - 01:28 AM

Was This Post Helpful? 0
  • +
  • -

#3 jimblumberg  Icon User is offline

  • member icon


Reputation: 4142
  • View blog
  • Posts: 12,896
  • Joined: 25-December 09

Re: Array offsets and Pointers

Posted 20 March 2013 - 06:34 AM

Quote

Seems like this should work to me from basic pointer arithmetic but it's not working for me.


Why doesn't it seem to be working for you? How are you trying to determine that it is or is not working?

Jim
Was This Post Helpful? 0
  • +
  • -

#4 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3623
  • View blog
  • Posts: 11,291
  • Joined: 05-May 12

Re: Array offsets and Pointers

Posted 20 March 2013 - 09:24 PM

Or put another way: if you are assuming that pointer + X, gives you the X-th item, when X is 1, are you expecting to get the 1st item? Why or why not?
Was This Post Helpful? 1
  • +
  • -

#5 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1086
  • View blog
  • Posts: 4,564
  • Joined: 09-June 09

Re: Array offsets and Pointers

Posted 22 March 2013 - 12:30 AM

Arrays start indexing at zero, look at the example below

int arr[5];
//init arr

int *first = arr + 0; //equivelent to &arr[0];
int *second = arr + 1;
ect..


This post has been edited by jjl: 22 March 2013 - 12:30 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1