In my comment on this answer ,
I am trying to copy this structure to flash [memory chip]. And the Flash reader / writer API passes the string. - Punit 2 hours ago
You will find that you have an XY problem - you are asking how to implement your idea of a solution, not how to solve your problem. You really do not want to copy the structure to the buffer, you want to write data in your structure to Flash using an API that requires the char * argument.
Others noted that memcpy will do what you want. But they all include memory allocation for this buffer in RAM. Using these approaches will work, but they will waste time and memory. Assuming your Flash API has a function:
int WriteBlock(int address, char *data, int length);
and you saved your structure in a variable called data_var , you can use your API like memcpy:
int success = WriteBlock(my_address, (char *) &data_var, sizeof(struct data)
To be clearer and avoid casting, you can wrap this in a union:
union { struct data{ int num1; int num2; int num3; int num4; }; char data_arr[sizeof(struct data)]; };
This will allow you to call it more traditional syntax.
Note that both methods (and memcpy!) Can fail if you have an non-contiguous structure. For example, perhaps your structure is as follows:
struct data{ int num1; char num2; long num3; short num4; }
If you use anything other than an 8-bit system, such a structure will probably (depending on your architecture) contain spaces. For example, if num1 is 0x12345678, num2 is 0x9A, num3 is 0xBCDEF0123456789A, and num4 is 0xBCDE, you might have the following: it is assumed that your memory has zero initialization, and for clarity - in big-endian format):
/ * 8-bit * /
0x1234 5678 9ABC DEF0 1234 5678 9ABC DE00
/ * 16-bit * /
0x1234 5678 009A BCDE F012 3456 789A BCDE
/ * 32-bit * /
0x1234 5678 0000 0000 0000 009A BCDE F012 3456 789A 0000 0000 0000 BCDE
In this case, you will need to use something uglier, like the following function:
int fillDataBuffer(struct data d, char *buffer, int len) { int i, j = 0; for (i = sizeof(d.num1) - 1; i >= 0 && j < len; i--, j++) { buffer[j] = (char) (d.num1 >> i); } for (i = sizeof(d.num2) - 1; i >= 0 && j < len; i--, j++) { buffer[j] = (char) (d.num2 >> i); } for (i = sizeof(d.num3) - 1; i >= 0 && j < len; i--, j++) { buffer[j] = (char) (d.num3 >> i); } for (i = sizeof(d.num4) - 1; i >= 0 && j < len; i--, j++) { buffer[j] = (char) (d.num4 >> i); } if (j >= len) { return 0; } else { return 1; } }
or the macro #pragma pack() , but this can make calculations using the structure slower, and you are likely to pack it when you do buffering.