Take the 2-minute tour ×

I have a string which I need to pass to a function like below.



char name[MAX];

I am getting the following warning :

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[50]’ [-Wformat]

I did try to do changes like having one more char pointer and point to name. But the warning stays.

In the function I have strcpy


This is coping the name from main to the name in the structure addnode. But there is a segmentation fault at this line.

I tried to check in splint (did not have any issues at this line) and valgrind but could not identify my mistake. Hence came here for help. Thanks in advance..

The code:

typedef struct Mystruct{
char *name;
int telno;
struct Mystruct *nextp;

void addatend(int telno1, char* name1)
    data *addnode, *previousnode;
    addnode = malloc (sizeof(data));

    if(addnode == NULL)
        printf("Memory allocation failed...Exiting");

    strcpy(addnode->name,name1);        //error Part of the code.
share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

When reading a string with scanf, the array is passed to the function as a pointer, so you don't need the address-of operator &.

Regarding your second problem... You need to allocate memory for the destination you copy to as well. Either use malloc again (using strlen(...) + 1, the +1 for the string terminator) before the strcpy, or use strdup which allocates and copies the string:

addnode->name = strdup(name1);
share|improve this answer
Ok thanks. I got the warnings cleared but the seg fault stays. Would you like to see the complete code once? –  Shash Dec 10 '12 at 10:27
@Shash Have you allocated memory for addnode and addnode->name? –  Joachim Pileborg Dec 10 '12 at 10:29
@Shash Please edit your question adding that code, and also the definition of the data structure. –  Joachim Pileborg Dec 10 '12 at 10:32
@Shash Updated my answer. –  Joachim Pileborg Dec 10 '12 at 10:44
add comment

You can also use zero-length array or flexible array member to store the name in your structure. However, it must be the last struct member. Here is how you declare it.

typedef struct Mystruct {
    int telno;
    struct Mystruct *nextp;
    char name[];
} data;

In the function, you would do

data *addnode = malloc(sizeof(data) + strlen(name1) + 1);
strcpy(addnode->name, name1);
share|improve this answer
add comment

Your Answer


