Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

c - Assign pointer contents to variable

Given a large struct pointer, say, large_ptr, and I want to assign it to a global var of the same type, let's call it g_large, then I have 2 options:

The first one using memcpy:

memcpy(&g_large, large_ptr, sizeof(g_large));

The second one using assignment:

g_large = *large_ptr;

Due to lack of memory and stack size in an embedded software I would like to know, does the second way behave like memcpy, or does it create a tmp var to do the assignment? Is there any standard for this?

If it behaves like memcpy then I'd prefer it for being shorter. But if it creates a temporary var, it might be a problem for the stack.

Your experience & knowledge will be appreciated!

Edit

A few mentioned I need to compile and view the assembly. This is a process I need to learn, since it's a cross compiler, which generates asm files that are binary and need to be parsed. Not a simple task. I could do that, but it will take time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I may misunderstood but in ur memcpy function the sizeof(g_large) will always return 8 bytes as result since the size of a pointer in c is 8 bytes. Therefore you get the pointer size and not the struct size. It's like you can not find the size of an array if you only have the pointer addressing it.

[edit: oh yeah i misunderstood but anyway the following section is still recommended]

What I would do:

  • dinamically allocate memory in main function
  • pass the allocated memory pointer to the local function where you want to work with your struct
  • extend the allocated memory if needed while working with your struct on the designated memory space
  • at the end of the local function you will already have ur struct stored in main function memory space without any copy function needed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...