Read bytes from data in memory

I need to copy bytes from data stored in memory. I need to begin copying from a starting point within this data and only copy a specific amount of bytes. Here is an example of how I have stored the data:

1
2
3
4
void *vertices = malloc(sizeof(float)*8);
memcpy(vertices, (void*)dataSrc, sizeof(float)*8);

// now "vertices" holds data 

I would like to copy the first 3 floats from the "vertices" buffer, then the second 3 floats, then the last 2 floats...how can I access this information?
If you want to put the data into actual float objects:

1
2
3
4
5
float* theData = (float*) vertices; // point at start of data
float floatOne = *theData; // read first float
theData++; // now pointing at next float in data
float floatTwo = *theData; // read second float
theData++; // now pointing at next float in data 


and so on.
Last edited on
what if some of the data is of another type..?
the data may also contain integers...

is there a way to build a template struct that will hold the data?
01101001

Unfortunately, if someone give the bits above and ask what they mean, nobody might be able to answer as long as that person explain what it is.

Compiler needs to know what type of variable it is to read the data in it. If you create memory buffer and give access by void pointer, you actually lose the way to let the computer know how to read the data.

That is the reason why Moschops used type casting to somehow explain to compiler that data is floating point numbers. (Actually it can be anything!)

Because malloc just gives void pointer, it is better to cast it right away and give it to typed pointer to let compiler know it is float for the rest of the time.

1
2
3
4
// I got some memory buffer here. You must read it as float
float* vertices = (float*)malloc(sizeof(float)*8);
// OK I know it is float. Let me assign floating point value there
vertices[0] = 3.4f;



Compiler cannot just read randomly mixed data in run-time. At least it needs to know some kind of rule such as struct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct Vertex
{
  int a;
  float b;
}
int main( void )
{
  /*
 Now each Vertex is 4 + 4 bytes long, It will give (4 + 4) * 8 bytes long
 memory buffer which supposed to save in sequence "integer float integer 
float ..."
 */
 
  struct Vertex* vertices = (struct Vertex*)malloc(sizeof(Vertex)*8);

  /* Create new Vertex and assign to the first */
  Vertex v;
  v.a = 0;
  v.b = 3.4f;
  vertices[0] = v;
}



Last edited on
Topic archived. No new replies allowed.