Oscar Wilson
Oscar Wilson

Reputation: 59

Initialising Struct in C using Parameters

(Fairly new to C) I have a struct I am trying to initialise and populate with variables. Defined by:
(I cannot edit the definition of the struct)

typedef struct metadata {
    off_t size;                 
    char name[50];  
} metadata_t;

When trying to initialise a 'metadata' object using parameters in a function defined by:

send_metadata(off_t file_size , char* output_file){

    metadata_t meta = {file_size , output_file};
    //send metadata to....

}

However get warning:

initialization of ‘char’ from ‘char *’ makes integer from pointer without a cast [-Wint-conversion]
     metadata_t meta = {file_size , name_buf};
                                    ^~~~~~~~

What is the proper way to accomplish what I'm trying to do

Upvotes: 0

Views: 31

Answers (1)

SergeyA
SergeyA

Reputation: 62563

You can not initialize an array from the pointer (meta = {file_size , output_file}; tries exactly that).

Instead, you should copy string value, like that:

metadata_t meta;

meta.size = file_size;
strncpy(meta.name, output_file, sizeof(meta.name));
meta.name[sizeof(meta.name) - 1] = '\0';

Note how strncpy is used (which limits the number of characters copied to array), and how the last element is set to null terminator, since strncpy would not do this if it had to truncate the string.

Upvotes: 2

Related Questions