2016-11-04 6 views
0

における構造体の文字列フィールドの割り当て:は、私は文字列を含むこの構造を使用してプログラムを書いてみるC

行あたりの設定テキストファイルの行を解析
typedef struct s_conf 
{ 
    char *shell1; 
    char *shell2; 
    char *shell3; 
    char *shell4; 
    char *server_ip;  
} t_conf; 

を、私は、この情報を取得し、私は変数にそれを保存しますline1とline4のように。

char *line1 = "/var/www/host/current/app/console robot:file"; 
char *line4 = "192.168.00.00"; 

t_conf *conf; 
if ((conf = malloc(sizeof(t_conf))) == NULL) 
     { 
      fprintf(stderr, "Malloc error\n"); 
      return (-1); 
     } 

strcpy(conf->shell1, line1); 
strcpy(conf->server_ip, line4); 

printf("line1 : '%s'\n"; line1); 
printf("line4 : '%s'\n"; line4); 

printf("t_conf->shell1 : '%s'\n", conf->shell1); 
printf("t_conf->server_ip : '%s'\n", conf->server_ip); 

出力:

line1 : '/var/www/host/current/app/console robot:file' 
line4 : '192.168.00.00' 
t_conf->shell1 : '/var/www/host/current/app' 
t_conf->server_ip : '192.168.00.00' 

正しくC文字列t_conf-> shell1を割り当てる方法を今、私は私の構造体は、変数LINE1及びLINE4の値をフィールドに割り当てたいですか? 私はmemcpy()、strdup()のような他の関数を試して、変数mallocを割り当てます:t_conf->shell1 = malloc(strlen(line1) + 1)しかし、それは私に同じ結果を与える、私はline1の一部を失う?

あなたはさらに、(コメントで@catで指摘したように) strcpyは危険であり、生産コードで避けなければならない、代替 strdup(非標準)、または snprintfある line1

を格納するスペースが必要

答えて

1
strcpy(conf->shell1, line1); 

size_t size = strlen(line1) + 1; 
conf->shell1 = malloc(size); 
snprintf(conf->shell1, size, "%s", line1); 

このスペースは、不要になったときにfree(conf->shell1);と返されます。

あなたはこれらの文字列を変更する必要がない場合は、あなただけの割り当て、コピーする必要はありませんconf->server_ip

注同じ:

conf->shell1 = line1; 
+0

'strcpy'と' strndup'を使用しないでください。代わりに、 'strndup'と' strnlen'はPOSIX.1-2008です。 – cat

+1

@cat:あなたはおそらくstrdup(左側)を意味します。また、 'strlcpy'も良い選択です。 – Aif

+1

@catあなたが編集したIMOは、標準よりもsnprintfです。 –

1

私はプログラムを書いてみます文字列を含むこの構造を使用して:

struct s_confは、以下の5つのポインタが含まの文字列は含まれていません。 C標準ライブラリでは、文字列配列(最終ヌル文字('\0')まで)です。コードを動作させるには、これらの配列のメモリが必要です。 conf->shell1はまだコピーに使用可能なメモリを指す値を持っていないので、

typedef struct s_conf { 
    char *shell1; 
    char *shell2; 
    char *shell3; 
    char *shell4; 
    char *server_ip;  
} t_conf; 

strcpy(conf->shell1, line1);は失敗します。


これらの5つのポインタに、必要なデータを含むメモリを示す値を設定します。


strdup()

// allocate memory for the structure 
conf = malloc(sizeof *conf); 
assert(conf); 

// Simply copy the pointer if `line1` will exist for as long as `conf`. 
conf->shell1 = line1; 

// or 
// Create an allocated copy. 
conf->shell1 = strdup(line1); 
// With this method, be sure to free the memory before freeing conf 
... 
free(conf->shell1); 
free(conf); 

は、標準ライブラリ関数、まだ非常に一般的ではありません。必要に応じて等価物を作る。例:(あなたのニーズに合わせて)

char *my_strdup(const char *s) { 
    if (s) { 
    size_t sz = strlen(s) + 1; 
    char *dest = malloc(sz); 
    if (dest) { 
     return memcpy(dest, src, sz); 
    } 
    } 
    return NULL; 
} 
関連する問題