473,671 Members | 2,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

bulk assignment to structure

I know I can assign default values to a structure during
initialization, but I have a routine that accumulates a lot of floats
into an array, and then I would like to assign them to a (reference to
a) structure before exiting. I would like something analogous to
strcpy, but for structures. My example:

in file foo.h:
-----------------------------------
struct _stats {
float slope;
float mpd;
float macro_sum;
float grabf[13][6];
};
typedef struct _stats t_stats;

t_stats ts_min;

in file foo.c:
-----------------------------------
#include "foo.h"

void some_routine_to _reset_ts_min(v oid) {
int i;
float *p_to_ts_min;
float some_array[81]= {0.01, 0.02, 0.03 ... 0.81};

// now populate the global ts_min structure
// it would be great to have the equivalent of strcpy, like
structcpy(ts_mi n, some_array);

// assigning by element name is tedious and prohibits easy code
change of
// constants determined from lab results like:
ts_min.slope = 0.01; // doable but difficult to revize
constants

// is it valid to do the following?
p_to_ts_min = &ts_min;
for (i=0; i<81; i++) {
p_to_ts_min[i] = some_array[i];
}
}

Is there a better way to do this?
Nov 13 '05 #1
7 2707
Read about the function memcpy(). This function basicalyl copies X number
of bytes from one memory location to the other. This should help you out.

Kris

"Brian K. Michalk" <mi*****@awpi.c om> wrote in message
news:c3******** *************** **@posting.goog le.com...
I know I can assign default values to a structure during
initialization, but I have a routine that accumulates a lot of floats
into an array, and then I would like to assign them to a (reference to
a) structure before exiting. I would like something analogous to
strcpy, but for structures. My example:

in file foo.h:
-----------------------------------
struct _stats {
float slope;
float mpd;
float macro_sum;
float grabf[13][6];
};
typedef struct _stats t_stats;

t_stats ts_min;

in file foo.c:
-----------------------------------
#include "foo.h"

void some_routine_to _reset_ts_min(v oid) {
int i;
float *p_to_ts_min;
float some_array[81]= {0.01, 0.02, 0.03 ... 0.81};

// now populate the global ts_min structure
// it would be great to have the equivalent of strcpy, like
structcpy(ts_mi n, some_array);

// assigning by element name is tedious and prohibits easy code
change of
// constants determined from lab results like:
ts_min.slope = 0.01; // doable but difficult to revize
constants

// is it valid to do the following?
p_to_ts_min = &ts_min;
for (i=0; i<81; i++) {
p_to_ts_min[i] = some_array[i];
}
}

Is there a better way to do this?

Nov 13 '05 #2
"Brian K. Michalk" wrote:

I know I can assign default values to a structure during
initialization, but I have a routine that accumulates a lot of floats
into an array, and then I would like to assign them to a (reference to
a) structure before exiting. I would like something analogous to
strcpy, but for structures. My example:

in file foo.h:
-----------------------------------
struct _stats {
float slope;
float mpd;
float macro_sum;
float grabf[13][6];
};
typedef struct _stats t_stats;

t_stats ts_min;

in file foo.c:
-----------------------------------
#include "foo.h"

void some_routine_to _reset_ts_min(v oid) {
int i;
float *p_to_ts_min;
float some_array[81]= {0.01, 0.02, 0.03 ... 0.81};

// now populate the global ts_min structure
// it would be great to have the equivalent of strcpy, like
structcpy(ts_mi n, some_array);

// assigning by element name is tedious and prohibits easy code
change of
// constants determined from lab results like:
ts_min.slope = 0.01; // doable but difficult to revize
constants

// is it valid to do the following?
p_to_ts_min = &ts_min;
for (i=0; i<81; i++) {
p_to_ts_min[i] = some_array[i];
}
}
No, because there can be padding after any element in
a struct. Some of your `some_array' values may land in
those padding positions.
Is there a better way to do this?


Many. I'd suggest something like:

float *p = some_array;

ts_min.slope = *p++;
ts_min.mpd = *p++;
ts_min.macro_su m = *p++;
for (i = 0; i < 13; ++i) {
for (j = 0; j < 6; ++j)
ts_min.grabf[i][j] = *p++;
}

You might (or might not) feel like substituting memcpy()
for the inner loop.

A question: Is there any reason why some_array must
actually be an array? If it were an instance of a struct
_stats object (bad choice of name, by the way), you could
copy the whole business with one single assignment.

--
Er*********@sun .com
Nov 13 '05 #3
On Thu, 2 Oct 2003 17:06:18 UTC, "Kris Wempa"
<calmincents(NO _SPAM)@yahoo.co m> wrote:
Read about the function memcpy(). This function basicalyl copies X number
of bytes from one memory location to the other. This should help you out.


No, it doesn't. An array is NOT a struct. The only you will get is
undefined behavior.

The only you may do is to define a static struct that gets initialised
with a set of default values. You can copy that struct into another my
memcpy. But copying an array into a struct would not work because a
struct may use another set of padding bits than a single variable or
an array uses. Maybe it works in your implementation now - but change
the version of your compiler or any other member of your
implementation and it fails.

--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch wird jetzt ausgeliefert!
Nov 13 '05 #4
I wasn't implying that it was going to solve all the issues. However, it
comes in handy in many cases and was close to what he was trying to do.

"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote in message
news:wmzsGguTDN 6N-pn2-ctw2npj5F5x2@mo on...
On Thu, 2 Oct 2003 17:06:18 UTC, "Kris Wempa"
<calmincents(NO _SPAM)@yahoo.co m> wrote:
Read about the function memcpy(). This function basicalyl copies X number of bytes from one memory location to the other. This should help you
out.
No, it doesn't. An array is NOT a struct. The only you will get is
undefined behavior.

The only you may do is to define a static struct that gets initialised
with a set of default values. You can copy that struct into another my
memcpy. But copying an array into a struct would not work because a
struct may use another set of padding bits than a single variable or
an array uses. Maybe it works in your implementation now - but change
the version of your compiler or any other member of your
implementation and it fails.

--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch wird jetzt ausgeliefert!

Nov 13 '05 #5
On Fri, 3 Oct 2003 15:40:59 UTC, "Kris Wempa"
<calmincents(NO _SPAM)@yahoo.co m> wrote:
I wasn't implying that it was going to solve all the issues. However, it
comes in handy in many cases and was close to what he was trying to do.

"The Real OS/2 Guy" <os****@pc-rosenau.de> wrote in message
news:wmzsGguTDN 6N-pn2-ctw2npj5F5x2@mo on...
On Thu, 2 Oct 2003 17:06:18 UTC, "Kris Wempa"
<calmincents(NO _SPAM)@yahoo.co m> wrote:
Read about the function memcpy(). This function basicalyl copies X number of bytes from one memory location to the other. This should help you

out.

No, it doesn't. An array is NOT a struct. The only you will get is
undefined behavior.

The only you may do is to define a static struct that gets initialised
with a set of default values. You can copy that struct into another my
memcpy. But copying an array into a struct would not work because a
struct may use another set of padding bits than a single variable or
an array uses. Maybe it works in your implementation now - but change
the version of your compiler or any other member of your
implementation and it fails.


It doesn't solve a single issue. using memcpy() for any other type
than (un)signed char is never a solution - except you use for both
bointers objects to the same type. An array is not a single object,
even as itself is a boundle of objects. A struct is not an array even
as you can make an array of struct. A float, int or struct is not an
array of bytes. You may however use a mem...() function to topy one
object of a type to another object of the same type but when you
starts to mixup the types you goes into the lands of undefined
behavior.

Undefined behvior means it can work with the current translation - but
fail with next one, another version of your compiler, another date or
only because it rains or the sun shines. It may work during debug but
will fail in production, it can do anything you expect or ever fail.
It can ever work at moday and ever fail on wednesday, it works on your
burthday but fails on any other day or reverse.

Whenever you have a problem with your data you have decided for a
wrong data layout. You should redesign your data layout. Not only when
your piece of data is object of change you should build a single
module that handles this kind. Then if the change occures rework this
module only and it's done. Make clean interfaces to it and you won.

Programming is a serie of design steps before coding:
- define the whole data layout
- test it, when test fails repeat the previous step
- define you program layout depending on the data layout
- test it, when it fails repeat the steps prior
- define clean interfaces
- test them, when failed repeat with one of the steps above
- write modular code that is able to handle the data
- test it, when failed repeat with one of the prior steps
- write modular code that makes its interaction with the souce of the
data
- test it, when failed repeat with one of the prior steps
- write modular code that makes its interaction with the destination
of the data
- test....
- write modular code that reflects the whole data flow
- test...
- write main() to bind all the modules to bind them right together
- test...
- retest....
- let the DAU test it....
release the program
wait for bug reports

You'll spend more time to get the data model working right than for
all other
You'll spend more time to get the program flow right than for coding
it
You'll spend more time for designing the user interaction than for
coding it

Whenever you starts without a clean and tested data model you'll loose
a multiple of time as when you had spent many time to get it clean
before starting to write the very first statement.

Then you would never come to the problem that you would copy an array
into a structure.

--
Tschau/Bye
Herbert

eComStation 1.1 Deutsch wird jetzt ausgeliefert!
Nov 13 '05 #6
"Kris Wempa" <calmincents(NO _SPAM)@yahoo.co m> wrote in message news:<bl******* **@kcweb01.netn ews.att.com>...
I wasn't implying that it was going to solve all the issues. However, it
comes in handy in many cases and was close to what he was trying to do.


1. top posting in clc is generally frowned upon.
2. read the clc faq before posting again. the link to the
faq is in most of the regulars signature.

hth
goose,
no sig yet
Nov 13 '05 #7
Eric Sosman <Er*********@su n.com> wrote in message news:<3F******* ********@sun.co m>...
No, because there can be padding after any element in
a struct. Some of your `some_array' values may land in
those padding positions.
Yes, I knew that, but thought some wizard might have some library that
would allow it like for initialization. I'me sure when it's
initialized, it acually happens at compile time, and that's why it
doesn't work at run time.
Many. I'd suggest something like:

float *p = some_array;

ts_min.slope = *p++;
ts_min.mpd = *p++;
ts_min.macro_su m = *p++;
for (i = 0; i < 13; ++i) {
for (j = 0; j < 6; ++j)
ts_min.grabf[i][j] = *p++;
}
That actually very close to what I already wrote. I was curious if
there were an easier way.
A question: Is there any reason why some_array must
actually be an array? If it were an instance of a struct
_stats object (bad choice of name, by the way), you could
copy the whole business with one single assignment.


Well, yes. I'm using an external library that is automatically
generated by some neural network software. It takes an array of
floats, but when I generate the statistics it's much easier to use the
structure.
Nov 13 '05 #8

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

Similar topics

23
3222
by: Paul Rubin | last post by:
OK, I want to scan a file for lines matching a certain regexp. I'd like to use an assignment expression, like for line in file: if (g := re.match(pat, line)): croggle(g.group(1)) Since there are no assignment expressions in Python, I have to use a temp var. That's a little more messy, but bearable:
6
13377
by: Neil Zanella | last post by:
Hello, I would like to know whether the following C fragment is legal in standard C and behaves as intended under conforming implementations... union foo { char c; double d; };
3
8088
by: Kiran | last post by:
Hi, I want to back up my data in some table in SQL server and import it back using Bulk Load of SQL server 2K. I can use the following code to backup the data in XML dataset.WriteXml(@"C:\Data.xml"); dataset.WriteXmlSchema(@"C:\Schema1.xml");
3
2807
by: Thyagu | last post by:
Hi, Is there any .NET package/module/assembly for BCPing the data into SQL Server. The BULK INSERT utility works fine, but we are kind of worried on placing the data. If there is any utility to build the data into a data structure and BCP in into the SQL Server, please let know. It would be of great use.
5
4041
by: Hallvard B Furuseth | last post by:
Does struct assignment copy padding bytes? Some compilers do, but I couldn't find anything in the standard which says they must. What I need is for any padding bytes to contan initialized values before fwrite(), to shut up memory debuggers like Valgrind about writing uninitialized data to the file. Simplified code: static const struct S default_value = ...; struct S s, t;
5
2018
by: subramanian | last post by:
Consdier the following program: #include <stdio.h> struct typeRecord { int id; char str; } records = { {0, "zero"}, {1, "one"},
0
4171
by: Peter Nofelt | last post by:
Hi all, ISSUE: ==================== In SQL 2005 (sp2) I get the following error when preforming a bulk insert with an associated xml format file: "Could not bulk insert. Unknown version of format file" Question:
6
3336
by: =?Utf-8?B?bWljaGFlbCBzb3JlbnM=?= | last post by:
Yesterday Visual Studio gave me a strange error both at compiletime and at designtime that had no obvious connection to anything I had changed recently. After some effort tracking down the problem I discovered first a workaround, then the real cause of the problem. I would like to understand why what I am doing is frowned upon by Visual Studio and how to do this properly. My application is in one solution; supporting libraries including...
0
8481
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
8400
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8924
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...
1
8602
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
8672
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7441
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...
0
5702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
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...
2
1814
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.