The problem of passing a string literal as a function parameter

Please check out this program.

#include<stdio.h> #include<string.h> typedef struct hs_ims_msrp_authority { int host_type; char buf[50]; int port; }hs_i; int main() { char dom[50]; int i = 10, j = 20; strcpy(dom, "ine"); fun((hs_i){i, dom, j}); // doesnt work fun((hs_i){i, "dom", j}); // this works } int fun(hs_i c) { printf("%d %s %d\n", c.host_type, c.buf, c.port); } 

In the fun function call in main; how does a function call work when a string literal ("dom") is passed, where, when an array variable (dom) is passed, does it not work?

To do work with variables, should it be typed in a certain way? or is there any other way?

+6
source share
3 answers

Having a composite literal is distracting, and the cause of the error is an attempt to initialize char[] another array of char[] . The following is not valid:

 char dom[50] = "test"; char dom1[50] = dom; /* Line 16, the cause of the error. */ 

and clang reports the following error:

main.c: 16: 10: error: array initializer must be an initializer list or a string literal

Point 14 in section 6.7.8 Initialization of C99 standard states:

A character type array can be initialized with a character string literal, optionally enclosed in braces. Successive characters of a character string literal (including a terminating null character if there is space or an array of unknown size) initialize the elements of the array.

Thus, a call with the string literal "dom" allowed, since it is legal to initialize an array with a string literal, but a call with char[] not allowed.

Possible solutions:

  • change buf type to const char*
  • wrap the buf element in a struct that will allow it to be copied. For instance:

     struct char_array { char data[50]; }; typedef struct hs_ims_msrp_authority { int host_type; struct char_array buf; int port; } hs_i; struct char_array dom = { "ine" }; int i = 10, j = 20; fun((hs_i){i, dom, j}); fun((hs_i){i, { "dom" }, j}); /* Note ^ ^ */ 
+3
source

In this case

 fun((hs_i){i, dom, j}); 

you just pass a pointer to a string. In other words, you just pass

&"ine"[0]

+1
source

First of all, you need to forward the declaration of your function:

  fun(hs_i c) 

Secondly, you need to create storage for your structure, so you need a temporary variable.

  hs_i temp = { i, NULL, j }; strcpy(temp.buf, "ine") fun(temp); 

Or pass your function as separate variables:

  fun(int host_type, char *buf, int port); .... fun(10, "ine", 20); ..... int fun(int host_type, char *buf, int port) { printf("%d %s %d\n", host_type, buf, port); } 
0
source

All Articles