Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help with accessing a char array from a pointer 1

Status
Not open for further replies.

Flappy

Programmer
Jul 30, 2002
35
AU
this has me stumped... ok this is what im trying to do..

i have a structure with alot of char*'s within it - when the user inputs a new value of one of the char* members the program updates that members' value - i've left out the free commands and other stuff to make this code a bit easier for you to read...

for testing reasons ive assigned the fgcolor member a value so i can see if the program is reaching its value but it i cant seem to reach it - i can access the location within the page structure of the member but i dont know how to access what it points to... ive also tried (char**) with no avail..

Code:
struct command {
  char* cmd;
  char* ptr;
};

struct page {
  char* title;
  char* bgcolor;
  char* fgcolor;
  struct command** cmd;
};

void init(struct page* obj) {
  char* cmd_arr[]={"title","bgcolor","fgcolor",NULL};
  char fgcolor[]="#0000FF";
  int len,i;

  obj->fgcolor=(char*)malloc(strlen(fgcolor)+1);
  strcpy(obj->fgcolor,fgcolor);

  for(len=0;cmd_arr[len]!=NULL;len++);

  obj->cmd=(struct command**)calloc(len,sizeof(struct command*));

  for(i=0;i<len;i++) {
    obj->cmd[i]=(struct command*)calloc(1,sizeof(struct command));
    obj->cmd[i]->cmd=(char*)malloc(strlen(cmd_arr[i])+1);
    strcpy(obj->cmd[i]->cmd,cmd_arr[i]);
    obj->cmd[i]->ptr=(char*)obj+(i+sizeof(char*));  // <--- THIS LINE
  }
}

I want the variable obj->cmd[n]->ptr to point to the members' value, but it will only return back to me the location of the member within the page structure

please help
 
Something like this?
Code:
  for(i=0;i<len;i++) {
    obj->cmd[i]=(struct command*)calloc(1,sizeof(struct command));
    obj->cmd[i]->cmd=(char*)malloc(strlen(cmd_arr[i])+1);
    strcpy(obj->cmd[i]->cmd,cmd_arr[i]);
//    obj->cmd[i]->ptr=(char*)obj+(i+sizeof(char*));  // <--- THIS LINE
    {
      char    **p = (char**)obj;  // pretend start of obj is an array of char pointers
      obj->cmd[i]->ptr = p[i];
    }
  }

> (i+sizeof(char*))
At the very least, this should be i*sizeof(char*)

IMO, its usually a lot simpler to create a pointer of the correct type and let the compiler figure out the address arithmetic.

 
oh cool i didnt think of doing it like that :)

yea sorry about the typo with the (i+sizeof(char*)) i did mean i*sizeof..

thanks for that! saved me alot of headaches :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top