473,769 Members | 7,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

array copy via "struct-trickery"

Hi!

OK, lets try "array-copy":

{
char arrayA[3];
arrayA = (char[]){1, 2, 3};
}
it does *not* work since we're trying to make a fixed array-pointer
arrayA, point to another location/address (where there is an
"anonymous" array holding 1, 2 and 3)

hmmm.... but have a look at this:

/*** trickery-candy ****/
#define LEN 3

struct mystruct {
char arr[LEN];
};

{
char arrayA[LEN];
char arrayB[LEN] = {1, 2, 3};
*((struct mystruct *)arrayA) = (struct mystruct){{1, 2, 3}};
*((struct mystruct *)arrayA) = *((struct mystruct *)arrayB);
}
/***************/

->it works! Using no memcpy (from string.h) or any other "normal
method"!!

Would the code for this be very similar to
memcpy(arrayA, arrayB, sizeof(arrayA)) ;
??? (How does it compare?)

(Any other ways of doing this?)

Regards -Albert

Aug 28 '07 #1
8 2170
an*******@gmail .com writes:
#define LEN 3

struct mystruct {
char arr[LEN];
};

{
char arrayA[LEN];
char arrayB[LEN] = {1, 2, 3};
*((struct mystruct *)arrayA) = (struct mystruct){{1, 2, 3}};
*((struct mystruct *)arrayA) = *((struct mystruct *)arrayB);
}
I'd recommend not doing that. For one thing, the compiler is
allowed to insert padding at the end of 'struct mystruct', so
that the structure assignment will actually write beyond the end
of the array. For another, even in the absence of trailing
padding, I suspect that the behavior is undefined given C's
aliasing rules.
--
"Your correction is 100% correct and 0% helpful. Well done!"
--Richard Heathfield
Aug 28 '07 #2
an*******@gmail .com writes:
OK, lets try "array-copy":
[snip]
>
hmmm.... but have a look at this:

/*** trickery-candy ****/
#define LEN 3

struct mystruct {
char arr[LEN];
};

{
char arrayA[LEN];
char arrayB[LEN] = {1, 2, 3};
*((struct mystruct *)arrayA) = (struct mystruct){{1, 2, 3}};
*((struct mystruct *)arrayA) = *((struct mystruct *)arrayB);
}
/***************/

->it works! Using no memcpy (from string.h) or any other "normal
method"!!
Sure. You can't assign arrays, but you can assign structures, even if
the structures have members that are arrays.
Would the code for this be very similar to
memcpy(arrayA, arrayB, sizeof(arrayA)) ;
??? (How does it compare?)
There's no reason to assume that the generated code would be
different, since it's doing exactly the same thing. The struct
assignment could well be implemented as a call to memcpy() -- or the
memcpy() call could be implemented as a sequence of MOVE instructions
(or whatever your CPU provides).

I'd just use memcpy() because it's clearer.
(Any other ways of doing this?)
Undoubtedly, but how many ways do you need?

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 28 '07 #3
On Aug 29, 8:33 am, Ben Pfaff <b...@cs.stanfo rd.eduwrote:
anon.a...@gmail .com writes:
{
char arrayA[LEN];
char arrayB[LEN] = {1, 2, 3};
*((struct mystruct *)arrayA) = (struct mystruct){{1, 2, 3}};
*((struct mystruct *)arrayA) = *((struct mystruct *)arrayB);
}

I'd recommend not doing that. For one thing, the compiler is
allowed to insert padding at the end of 'struct mystruct', so
that the structure assignment will actually write beyond the end
of the array. For another, even in the absence of trailing
padding, I suspect that the behavior is undefined given C's
aliasing rules.
The aliasing rules allow anything to be aliased as char,
I think. However, the behaviour would be undefined if
arrayA is not correctly aligned for a struct mystruct.

Aug 29 '07 #4
Old Wolf <ol*****@inspir e.net.nzwrites:
On Aug 29, 8:33 am, Ben Pfaff <b...@cs.stanfo rd.eduwrote:
>anon.a...@gmai l.com writes:
{
char arrayA[LEN];
char arrayB[LEN] = {1, 2, 3};
*((struct mystruct *)arrayA) = (struct mystruct){{1, 2, 3}};
*((struct mystruct *)arrayA) = *((struct mystruct *)arrayB);
}

I'd recommend not doing that. For one thing, the compiler is
allowed to insert padding at the end of 'struct mystruct', so
that the structure assignment will actually write beyond the end
of the array. For another, even in the absence of trailing
padding, I suspect that the behavior is undefined given C's
aliasing rules.

The aliasing rules allow anything to be aliased as char,
I think.
Sure. I am not enough of an expert on C's aliasing rules to know
whether a struct encapsulating an array of char would follow the
same aliasing rules as an array of char. I suspect that it would
not.
However, the behaviour would be undefined if arrayA is not
correctly aligned for a struct mystruct.
That's a third reason not to do this. Thank you.
--
char a[]="\n .CJacehknorstu" ;int putchar(int);in t main(void){unsi gned long b[]
={0x67dffdff,0x 9aa9aa6a,0xa77f fda9,0x7da6aa6a ,0xa67f6aaa,0xa a9aa9f6,0x11f6} ,*p
=b,i=24;for(;p+ =!*p;*p/=4)switch(0[p]&3)case 0:{return 0;for(p--;i--;i--)case+
2:{i++;if(i)bre ak;else default:continu e;if(0)case 1:putchar(a[i&15]);break;}}}
Aug 29 '07 #5
On Aug 29, 2:18 am, Old Wolf <oldw...@inspir e.net.nzwrote:
<snip>
However, the behaviour would be undefined if
arrayA is not correctly aligned for a struct mystruct.
Could it ever happen that arrayA is not correctly aligned with struct
mystruct, given the following:
#define LEN 3

struct mystruct {
char arr[LEN];
};

char arrayA[LEN];

Might the struct have padding? Would a union change the situation?

By the way - is a struct (or union) aligned according to its size, or
according to the largest component it contains?

Thanks -Albert

Aug 29 '07 #6
an*******@gmail .com writes:
On Aug 29, 2:18 am, Old Wolf <oldw...@inspir e.net.nzwrote:
<snip>
>However, the behaviour would be undefined if
arrayA is not correctly aligned for a struct mystruct.

Could it ever happen that arrayA is not correctly aligned with struct
mystruct, given the following:
#define LEN 3

struct mystruct {
char arr[LEN];
};

char arrayA[LEN];
Yes. Note that compilers are likely to allocate objects on stricter
alignment boundaries than they really need to, so code that assumes
arrayA is strictly aligned may happen to work (until it breaks at the
most inconvenient possible moment).
Might the struct have padding?
Yes.
Would a union change the situation?
No.
By the way - is a struct (or union) aligned according to its size, or
according to the largest component it contains?
The alignment for a struct or union is at least the alignment for its
most strictly aligned member. It may be more strict. For any type,
the size must be a whole multiple of the alignment.

For example char always has one-byte alignment. An implementation
might require, say, 4-byte alignment for all structures. In that
case, this structure:

struct foo {
char c;
};

would have 4-byte alignment; it would therefore have to have at least
3 bytes of padding after 'c'. This is just one possibility; a
compiler is also free to set the size and alignment of 'struct foo' to
1 byte.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 29 '07 #7
On Wed, 29 Aug 2007 02:19:02 -0700, an*******@gmail .com wrote:
>On Aug 29, 2:18 am, Old Wolf <oldw...@inspir e.net.nzwrote:
<snip>
>However, the behaviour would be undefined if
arrayA is not correctly aligned for a struct mystruct.

Could it ever happen that arrayA is not correctly aligned with struct
mystruct, given the following:
#define LEN 3

struct mystruct {
char arr[LEN];
};

char arrayA[LEN];

Might the struct have padding? Would a union change the situation?
Yes. No, a union may also
have padding.
>
By the way - is a struct (or union) aligned according to its size, or
according to the largest component it contains?
A struct is aligned to insure that every member is also properly
aligned.

Since all the members of a union overlap, it is aligned according the
strictest alignment of its members.
Remove del for email
Aug 31 '07 #8
Barry Schwarz <sc******@doezl .netwrites:
[...]
A struct is aligned to insure that every member is also properly
aligned.
At least.
Since all the members of a union overlap, it is aligned according the
strictest alignment of its members.
At least.

A struct or union may be more strictly aligned than any of its
members. For example, an implementation might choose to give all
structs and union 4-byte alignment, even if they contain only
character members.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Aug 31 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2454
by: Frank Passek | last post by:
Hi all, to handle a collection of data, I could use an associative array or a class. Provided I don't need any of the functionalities classes offer, i.e. use it as a struct, what is the better option in terms of speed? Cheers Frank
3
14506
by: Pablo Gutierrez | last post by:
I have a C# method that reads Binary data (BLOB type) from a database and returns the data an array of bytes (i.e byte outbyte = new byte;). The BLOB column is saved into the database by a C program (UNIX) as an array of "struct point" where struct point //C structure { int Time; //32 bits
3
4304
by: Pawe³ | last post by:
Hi! I want to read with C# some binary file with well defined binary structure. In C++ I was declaring appropriate struct, like: typedef struct {BYTE b1; WORD w1, w2; DWORD dw1} REKORD1; REKORD1 buff ; and then read record from file with read (file, (void *) &buff, sizeof (REKORD1));
10
2745
by: Pantokrator | last post by:
Hi, Is there any way to "overload" a struct? e.g. having already struct stA1 { int i_ID; int i_Type; };
3
4357
by: angshuman.agarwal | last post by:
Structure in C DLL ---------------------------- typedef struct IrData { unsigned short uiFormat; unsigned short uiLength; unsigned char* pchData; } tagIrData; Function in C DLL
8
28469
by: Mohammad Omer Nasir | last post by:
Hi, i made a structure in header file "commonstructs.h" is: typedef struct A { int i; A( ) {
8
40471
by: cman | last post by:
What does this kind of typedef accomplish? typedef struct { unsigned long pte_low; } pte_t; typedef struct { unsigned long pgd; } pgd_t; typedef struct { unsigned long pgprot; } pgprot_t I am familiar with "typedef int NUMBER", but how does it work with structures. Tilak
15
2681
by: arnuld | last post by:
-------- PROGRAMME ----------- /* Stroustrup, 5.6 Structures STATEMENT: this programmes *tries* to do do this in 3 parts: 1.) it creates a "struct", named "jd", of type "address". 2. it then adds values to "jd" 3.) in the end it prints values of "jd".
20
1859
by: Francine.Neary | last post by:
People seem to have different views as to where the C reserved word "struct" comes from. One explanation is that it is a shortening of "structure", and another is that it is an acronym for "single type representing useful compound types". Does anyone here know the history of the word?
4
10622
by: MetaKith | last post by:
Hi, Please have a look on the next code : struct foo{ float b; char z; }; struct foo foo_init = {234.77,"xcdy"}; struct foo *prt_prt=&foo_init;
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10219
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9998
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8876
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5310
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.