0

I am coping conf data from struct to char array buffer.Data copied successfully but problem is that null also copied from structures because of size. How can i get data without null.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_DEVICE    5
#define MAX_CONF_PORT 3

typedef struct
{
  unsigned char id[6];
  unsigned char domain[32];
  unsigned char ports[MAX_CONF_PORT][5];
}DEV_CONF_DATA; 

#define SIZE_OF_DEV_CONF_DATA sizeof(DEV_CONF_DATA)

typedef union {
  DEV_CONF_DATA data;
  unsigned char bytes[SIZE_OF_DEV_CONF_DATA];   
}DEV_CONF_BUFF;

typedef struct {
    DEV_CONF_BUFF conf[MAX_DEVICE];
}DEVICE;

int main()
{
  int i = 0;
  DEVICE device;
  unsigned char tx_buff[1024];
  unsigned char *dest_ptr = tx_buff;

  device.conf[0].data= (DEV_CONF_DATA) {"ABC,","embed-service.net,","8111,","8112,",","};
  device.conf[1].data= (DEV_CONF_DATA) {"XYZ,","embed-service.net,","7111,","7112,",","};

  memcpy(dest_ptr,device.conf[0].bytes,SIZE_OF_DEV_CONF_DATA);
  dest_ptr += SIZE_OF_DEV_CONF_DATA;
  memcpy(dest_ptr,device.conf[1].bytes,SIZE_OF_DEV_CONF_DATA);
  dest_ptr += SIZE_OF_DEV_CONF_DATA;

   for(i=0;i<SIZE_OF_DEV_CONF_DATA;i++)
       if( tx_buff[i] == 0)
       printf("%s", " null ");
       else
       printf("%c", tx_buff[i]);

   printf("\n\n\n");

   for(i=SIZE_OF_DEV_CONF_DATA;i<SIZE_OF_DEV_CONF_DATA*2;i++)
       if( tx_buff[i] == 0)
       printf("%s", " null ");
       else
       printf("%c", tx_buff[i]);
}

This is my output :

ABC, null null embed-service.net, null null null null null null null null null null null null null null 8111,8112,, null null null null

XYZ, null null embed-service.net, null null null null null null null null null null null null null null 7111,7112,, null null null null

enter image description here

i want neat clean data in buffer like this,

ABC,embed-service.net,8111,8112,,XYZ,embed-service.net,7111,7112,,

voidpointer
  • 301
  • 1
  • 8
  • 2
    Please do not post text output as graphics. Just select and copy from your shell and enter as plain text into your question. – Gerhardh May 28 '20 at 13:07
  • If you only want to have the content of your string, why do you print values after the terminator of that string? `printf` is good at printing whole strings. No need to print each character separately. – Gerhardh May 28 '20 at 13:09
  • its just for representation , i am transmiting this buffer over tcp/ip @Gerhardh – voidpointer May 28 '20 at 13:11
  • i dont want these nulls in my buffer – voidpointer May 28 '20 at 13:12
  • It would appear that you simply wish to use strlen + strcpy instead. – Lundin May 28 '20 at 13:33
  • 1
    How often will you be transmitting this buffer, and will you be sending more than one at a time? You might actually want to leave it the way it is to make serialization / deserialization easier. – dbush May 28 '20 at 13:45

0 Answers0