How to print char from struct

Can someone tell us to print char when receiving data as a structure? Here is an example:

...
struct rcv{
  int x1;
  float x2;
  char *x3;
}; 
rcv data_rcv;
...
if (recv(socket, &data_rcv, sizeof(data_rcv), 0) < 0)
printf("recv() failed");
...

printf("x1 = %d\n", data_rcv.x1);
printf("x2 = %f\n", data_rcv.x2); 

printf("x3 = %s\n", data_rcv.x3); // it doesn't print anything, why? 
...

Suppose x3 is passed line by line through a socket, as such:

...
char *str1="data-of-app.1"

struct snd{
  int x1;
  float x2;
  char *x3;
}; 
snd data_snd;
...
data_snd.snd = str1;
...
if (send(socket, &data_snd, sizeof(data_snd), 0) < 0)
printf("send() failed");
...

Thank you for your responses -

+3
source share
3 answers
printf("x3 = %s\n", data_rcv.x3);

it should be

printf("x3 = %c\n", data_rcv.x3);
+6
source

In your example is x3not char- it is a pointer to char. In most cases, pointer values ​​only make sense in the process from which they originally belonged. If you send the pointer value to another process through a socket, the receiving process usually cannot use it.

char (, , char, ) - struct :

struct rcv {
  int x1;
  float x2;
  char x3[LENGTH];
}; 

:

struct rcv {
  int x1;
  float x2;
  char x3;
}; 

( , %c %s printf).

, , , struct, , , .


:

struct , . :

#define N 100

struct rcv {
    int x1;
    float x2;
    char x3[N];
};

... x3, strcpy ( , strncat):

struct rcv data;

data.x3[0] = 0;
strncat(data.x3, some_string, N - 1);
+6

%stries to print a line with a terminating zero and expects the parameter to be a pointer char. Instead, it gets the value char(and since the pointer on all modern machines is bigger than char, it also gets some garbage after it), which is very bad.

You should use instead %c.

+4
source

Source: https://habr.com/ru/post/1736585/


All Articles