LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   structure inside a structure in C (http://www.linuxquestions.org/questions/programming-9/structure-inside-a-structure-in-c-4175426999/)

batman4 09-13-2012 03:09 AM

structure inside a structure in C
 
Pls help me with this programm..
Code:

#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>


#define BUFFSIZE 256
#define SMALL_SIZE 16
#define MED_SIZE 64
#define MAX  16
#define PORT 5555

char buffer[BUFFSIZE];

struct students
{
    int n;
    char Name[MED_SIZE];
    char Status[SMALL_SIZE];
};

struct Sending{
    int seqno;
    struct students class;
    struct Sending *next;

};
int main(){
    struct Sending *snd=NULL;
//  struct students *td =NULL;
//  char buf[BUFFSIZE] = "\0";
    snd = (struct Sending *)malloc(sizeof(struct Sending));

    memset(snd.class,0,sizeof(struct students));
    strcpy(snd.class->Name ,"PRIYA");
    printf("%s\n" ,snd.class->Name );
}


pan64 09-13-2012 03:46 AM

memset(snd.class,0,sizeof(struct students));
this line will segfault because snd.class is not initialized. malloc some memory before usage

NevemTeve 09-13-2012 04:06 AM

'snd' is a pointer, so it won't compile on the first place

dwhitney67 09-13-2012 06:52 AM

Code:

...

    memset(snd->class,0,sizeof(struct students));
    strcpy(snd->class.Name ,"PRIYA");
    printf("%s\n" ,snd->class.Name );

...

Avoid strcpy(); use strncpy() instead to avoid the possibility of overrunning a buffer.


All times are GMT -5. The time now is 10:43 AM.