I am trying to write a program to mimic some assembly code(don't ask me why lol), and it should look something like this.
It should use int value in order to populate the memory of the structure that consists of long values.
When I debug the program, in the first iteration sizeof(int)*a = 0
and everything is good.
But in the second iteration, a=1
and sizeof(int)*1=4
, but &ss+sizeof(int)*a
is not equal to &ss+4
but rather to &ss+0xA0
... Then for a = 2
, &ss+0x140
. It is constantly multiplying by 40 (decimal system).
hex 0xA0
= 4*40
decimal. hex 0x140
= 8*40
decimal...
How to make this work?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
long a[5];
} StructType1;
StructType1 foo()
{
StructType1 ss;
int bb = 7;
int a = 0;
while (a < 10)
{
memcpy(&ss + sizeof(int) * a, &bb, 4);
a++;
}
return ss;
}
int main()
{
StructType1 s = foo();
printf("%ld\n", s.a[0]);
}
As commented by user3386109, the type of &ss
is pointer to a StructType1
object, thus adding an integer n
to it computes the address of the n
-th next object in an array of such objects, multiplying n
by the size of the object to the get the byte address.
For you purpose, you should cast &ss
as a pointer to a character type.
Here is a modified version:
#include <stdio.h>
#include <string.h>
typedef struct {
long a[5];
} StructType1;
StructType1 foo(void) {
StructType1 ss;
int bb = 7;
int a = 0;
int n = sizeof ss / sizeof(int);
while (a < n) {
memcpy((char *)&ss + sizeof(int) * a, &bb, sizeof(int));
a++;
}
return ss;
}
int main() {
StructType1 s = foo();
for (int i = 0; i < 5; i++) {
printf("%ld%c", s.a[i], " \n"[i]);
}
return 0;
}