strings issues in C

store char array in array of structs

Page 1 of 1

3 Replies - 1039 Views - Last Post: 03 November 2005 - 02:01 AM Rate Topic: -----

#1 el wexican  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 28-September 05

strings issues in C

Posted 30 October 2005 - 09:02 PM

Figuring out how to dynamically allocate memory for a string was a pain, but now I can't figure out how to store the character arrays in an array of structures. My code is a nightmare and I am prety well lost at what I am supposed to do.

I need to store the first and last names of people in a structure and then display them as needed.

I think this is how the structure is going to look;

struct {
char* first_name;
char* last_name;
} name_stuff;

and the code for making the array looks a little something like this:

char a;
int i;
char* string1;
int counter = 1;
string1 = (char *)malloc(sizeof(char));

printf("Type your name:\n");

while((a != '\n') && counter != -1)
{
a = getchar();
string1 = (char*)realloc(string1, sizeof(char) * counter);
if(string1 == NULL)
{
counter = -1;
}else{
string1[counter - 1] = a;
counter++;
}
}
if(counter != -1)
{
string1 = (char*)realloc(string1, sizeof(char) * counter);
string1[counter] = '\0';
}

I would appreciate any help that is offered on this.

Is This A Good Question/Topic? 0
  • +

Replies To: strings issues in C

#2 Videege  Icon User is offline

  • rÍvant.toujours
  • member icon

Reputation: 6
  • View blog
  • Posts: 1,413
  • Joined: 25-March 03

Re: strings issues in C

Posted 30 October 2005 - 09:22 PM

Well, just some quick pseudo code here, but to put arrays of chars (here you are doing it by char *) into an array of structures like you have declared,

name_stuff[however_many_instances_you_need] structarray;

and then edit the names by

structarray[x].firstname //etc.
Was This Post Helpful? 0
  • +
  • -

#3 jaredolympia  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 29
  • Joined: 15-October 05

Re: strings issues in C

Posted 02 November 2005 - 07:24 PM

If the last guys didn't really help, I can give you a complete example. I recently did a rather large project containing structures with pointers so I should be able to help out.
Was This Post Helpful? 0
  • +
  • -

#4 el wexican  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 28-September 05

Re: strings issues in C

Posted 03 November 2005 - 02:01 AM

Hey thanks for offering, but I actually got the project finished a few days ago, more or less complete.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1