user3436838
user3436838

Reputation: 113

structure containing character array as its member in C linux

I know it's a simple question but not getting why it's giving error. Please help me in getting this very simple prog work. It's giving error and seg fault as shown below in comments.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct msgclient
{
    int msglen;
    int msgtype;
    char cp[100];
}M1;

int main()
{
    M1 *m;
    m=malloc(sizeof(M1));
    m->msglen=5;  
    m->msgtype=6; 
    m->cp="hi how are you";  //error

    printf("\n%d\n%d\n%s",m->msglen,m->msgtype,m->cp);
    return 0;
}

Thanks :)

Upvotes: 0

Views: 89

Answers (3)

Dabo
Dabo

Reputation: 2373

You need to allocate memory for your struct

 M1 *m= malloc(sizeof(M1)) ;

and use strncpy to copy string into array

 int n = strlen("hi how are you");
 strncpy(m->cp,"hi how are you",n);
 m->cp[n] = '\0';

m->cp ="hi how are you"; won't compile as you trying to assign address of array "hi how are you" to array cp, it is like writing &m->cp[0] = &"hi how are you"[0];

Upvotes: 0

Jabberwocky
Jabberwocky

Reputation: 50831

You must allocate memory for the m pointer. In your program the m pointer is not initialized, it contains garbage and it points most likely to invalid memory.

For example:

M1 *m = malloc(sizeof M1) ;

Or just not using a pointer like:

M1 m;
m.msglen=5;
m.msgtype=6;
strcpy(m.cp, "hi how are you"); // see also below

Other problem:

m.cp = "hi how are you" ;

or

m->cp = "hi how are you" ;

wont compile, you need to use the strcpy function. There is no real string type in C as it exists in other languages.

Upvotes: 1

James
James

Reputation: 9278

Your problem is

M1* m;

m is not initialised and will point to a random memory address. You need to do

M1* m = malloc(sizeof(M1));
...
strncpy(m->cp, "hi how are you", 15);
free(m);

Upvotes: 2

Related Questions