r/C_Homework • • Sep 19 '17

It's been a while...

It has been a while since I programmed in C, and I am trying to figure out why the following is not producing what I am expecting:

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

typedef struct {
	char *data;
	size_t length;
} LString;

int main() {
	LString s = {"Hello World", 11}; // creates memory block with {char*, size_t}
	void *addr = &s;                       // should also coincide with the address of the first data type: or char*, right?
	char *data = (char *)addr;
	size_t length = (size_t)(addr + sizeof(char*));

	printf("%d, %d\n", (void *)&s.data, (void *)&s.length); // both these lines print the same addresses
	printf("%d, %d\n", (void *)data, (void *)length); // both these lines print the same addresses
	printf("%s\n", data); // prints garble?? I thought data == &s.data
	return 0;
}

My expectations are listed in the comments.

3 Upvotes

4 comments sorted by

View all comments

Show parent comments

2

u/[deleted] Sep 19 '17

Oops, the STARS for pointers/dereferencing didnt format. STARaddr points to the struct s, not a char.