1

i want to use nested structures with pointers in c. i write this code but i dont know why this code not working. actually how can i allocate memory for my second structure?

#include <stdio.h>
#include <stdlib.h>
struct address
{
    int code;
    char city[10];
};
struct student {
    char name[10];
    struct address *ads;
} *person1;

int main()
{

person1 = malloc(sizeof(struct student));
scanf("%s", person1->name);
scanf("%d", &person1->ads->code);
scanf("%s", person1->ads->city);

printf("%s", person1->name);
printf("%d", person1->ads->code);
printf("%s", person1->ads->city);
return 0;
}

NOTE: when i use "person1->ads = malloc(sizeof(struct address));" program ran to problem and stop working.


[Update from comment:]

I use DEV C++ v5.4.2

6
  • 2
    You have not allocated memory for the ads member. So you need to add something like person1->ads = malloc(sizeof(struct address)); Commented Jan 11, 2015 at 12:40
  • i guess and test.. but program ran to problem Commented Jan 11, 2015 at 12:42
  • For this layout, I wouldn't make ads a pointer in the first place. Just declare it in struct student as struct address ads; and populate it with person1->ads. . Commented Jan 11, 2015 at 12:52
  • @WhozCraig you are right; but i want to test this way for myself. Commented Jan 11, 2015 at 12:56
  • @AmirMohammadNasrollahi The answers below are correct. You're not doing something right, and its too early/late for my code-clairvoyance to stab guesses. Amend your question with the attempt you currently have that incorporates either answer below. Don't replace your posted code; update the question with an EDIT content that shows exactly what you have now and how you're running it. Commented Jan 11, 2015 at 12:58

3 Answers 3

4

You need to also allocate memory for members stored via pointer.

int main()
{  
    person1 = malloc(sizeof(struct student));
    person1->ads = malloc(sizeof(struct address));
    scanf("%s", person1->name);
    scanf("%d", &person1->ads->code);
    scanf("%s", person1->ads->city);

    printf("%s", person1->name);
    printf("%d", person1->ads->code);
    printf("%s", person1->ads->city);
    free(person1->ads);
    free(person1);
    return 0;
}
Sign up to request clarification or add additional context in comments.

6 Comments

@AmirMohammadNasrollahi , Change int name[10]; to char name[10]; and it will work.
@CoolGuy ohhh sorry!! a mistake from me! :)
@CoolGuy but this not the main issue of this problem. my problem is about allocating memory and still not working...
@amir-mohammad-nasrollahi what exactly is not working? Please be more precise.
@AmirMohammadNasrollahi , I tested the code in TomaszKlak's answer and also changed what I've said in my previous comment and it worked. Try checking the return value of malloc to see if it failed.
|
3

You have a few poblems

  1. You don't check the success of malloc.
  2. You don't malloc for person1->ads member.
  3. You don't check the success of scanf.

This is a fixed and anotated version of your code

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

struct address
{
    int code;
    char city[10];
};

struct student
{
    char name[10];
    struct address *ads;
};

int main()
{
    /* You don't need te struct to be global, and it's generally a bad idea, not always of course */
    struct student *person;

    /* you should check that malloc succeeded otherwise undefined behavior would happen */
    person = malloc(sizeof(*person));
    if (person == NULL)
    {
        printf("cannot allocate memory\n");
        return -1;
    }

    /* you should check that scanf succeeded too */
    if (scanf("%9s", person->name) != 1)
    /*          ^ prevent buffer overflow */
    {
        printf("Invalid, input\n");
        free(person);
        return -1;
    }

    person->ads = malloc(sizeof(*(person->ads)));
    if (person->ads == NULL)
    {
        printf("cannot allocate memory\n");
        /* on failure free successfuly allocated person */
        free(person);
        return -1;
    }

    /* you should check that scanf succeeded too */
    if (scanf("%d", &person->ads->code) != 1)
    {
        printf("Invalid, input\n");

        free(person->ads);
        free(person);

        return -1;
    }

    /* you should check that scanf succeeded too */
    if (scanf("%9s", person->ads->city) != 1)
    /*          ^ prevent buffer overflow */
    {
        printf("Invalid, input\n");

        free(person->ads);
        free(person);

        return -1;
    }

    printf("Name: %s\n", person->name);
    printf("Code: %d\n", person->ads->code);
    printf("City: %s\n", person->ads->city);

    free(person->ads);
    free(person);

    return 0;
}

7 Comments

1+ for scaning with limits ... :-)
@AmirMohammadNasrollahi عفوًا
@iharob my language is Persian not ARABIC! i think you try to say 'خواهش میکنم' :)))
@alk there are more elegant ways of handling that, but just for ilustrative purposes I think it's ok.
Yes, sure. Just as I was used to ... ;-) @iharob
|
3

how can i allocate memory for my second structure?

For example the same way as you did for the first structure: allocate it from the heap

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

struct address
{
  int code;
  char city[10];
};

struct student 
{
  char name[10];
  struct address * ads;
};

int main(void)
{
  struct student * person1 = malloc(sizeof * person1);
  if (NULL == person1)
  {
    perror("malloc() failed for person1");
  }
  else
  {
    person1->ads = malloc(sizeof * person1->ads);
    if (NULL == person1->ads)
    {
      perror("malloc() failed for person1->ads");
    }
    else
    {
      /* scan and print */

      free(person1->ads);
    } 

    free(person1);
  }
}

6 Comments

okey i know!! but how? i test many ways and all of them not working! :D
good way and i understand it but still have problem with identifying "person1->ads" and stop working. i dont know why really your code not working in this compiler.
@AmirMohammadNasrollahi: Does it work if you comment out the scaning/printing code?
@AmirMohammadNasrollahi ,"...this compiler" Which compiler?
this version of C compiler which i use. i use DEV C++ v5.4.2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.