473,769 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing members of array as a different type

Hi,

I'm having trouble geting my head around this, although I know it's a pretty
basic question.

I have an application whereby an area of RAM is mapped to an array:

unsigned char NV[128];

Two consequtive elements are used to hold an unsigned int (2 bytes on this
platform). How do I access it as an unsigned int?

e.g.
unsigned int test;
....
test = *(unsigned int *)(&(NV[15]);

In this case, I'm trying to retrieve the unsigned int value represented by
elements 15 & 16 of the array. It does not seem to be working.

Could someone please explain what I'm doing wrong.

Many thanks,

James
Nov 14 '05 #1
7 1258
James A <me@privacy.net > wrote:
I'm having trouble geting my head around this, although I know it's a pretty
basic question. I have an application whereby an area of RAM is mapped to an array: unsigned char NV[128]; Two consequtive elements are used to hold an unsigned int (2 bytes on this
platform). How do I access it as an unsigned int? e.g.
unsigned int test;
...
test = *(unsigned int *)(&(NV[15]); In this case, I'm trying to retrieve the unsigned int value represented by
elements 15 & 16 of the array. It does not seem to be working.


It would be helpful to tell what you mean by "not seem to be working".
That construct could, for example, crash your program with a SIGBUS
error because of an unaligned access. Or it could work but deliver
an unexpected result. But what you expect is something that no-one
can figure out from what you write, so it could be that the numbers
you're expecting in memory are stored in big-endian order while you
try to do all of that on a little endian machine etc. Or it could
be because what you try to read belongs actually to two different
2-byte numbers (if, as you write, all the 128 bytes are occupied
by 64 2-byte numbers).
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2

"James A" <me@privacy.net > wrote in message
news:q6******** ******@newsfe2-gui.ntli.net...
Hi,

I'm having trouble geting my head around this, although I know it's a pretty basic question.

I have an application whereby an area of RAM is mapped to an array:

unsigned char NV[128];

Two consequtive elements are used to hold an unsigned int (2 bytes on this
platform). How do I access it as an unsigned int?

e.g.
unsigned int test;
...
test = *(unsigned int *)(&(NV[15]);

In this case, I'm trying to retrieve the unsigned int value represented by
elements 15 & 16 of the array. It does not seem to be working.

Could someone please explain what I'm doing wrong.


You don't give enough information. E.g.
How was the data originally stored?

#include <stdio.h>

int main()
{
unsigned char NV[128] = {0};
unsigned int test = 0;

NV[15] = NV[16] = 0xAA;
test = *(unsigned int *)(NV + 15);

printf("%u\n", test); /* prints 43690 for implementations with
*/
/* two-byte unsigned int and for 'little-endian'
*/
/* (e.g. most PC's) platforms with a larger
*/
/* unsigned int
*/

return 0;
}

-Mike

Nov 14 '05 #3
On Thu, 16 Sep 2004 18:40:22 GMT
"James A" <me@privacy.net > wrote:
I'm having trouble geting my head around this, although I know it's a
pretty basic question.

I have an application whereby an area of RAM is mapped to an array:

unsigned char NV[128];

Two consequtive elements are used to hold an unsigned int (2 bytes on
this platform). How do I access it as an unsigned int?

e.g.
unsigned int test;
...
test = *(unsigned int *)(&(NV[15]);
You seem to have mismatched brackets. I assume this was a typo and not
the problem in your actual code.
In this case, I'm trying to retrieve the unsigned int value
represented by elements 15 & 16 of the array. It does not seem to be
working.

Could someone please explain what I'm doing wrong.


What you are doing wrong is invoking undefined behaviour when you don't
need to. One reason why this might fail on real implementations is due
to alignment restrictions, other reasons for failure include having more
than 5 minutes in a day. Depending on what you are trying to achieve
something like
test = ((unsigned int)NV[15] << CHAR_BIT) || NV[16]
or possibly
test = ((unsigned int)NV[16] << CHAR_BIT) || NV[15]

Of course, if by "area of RAM is mapped to an array" you mean some RAM
written to by some other (e.g. if it is DPRAM) then you would also need
to declare NV as volatile.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #4
"Mike Wahler" <mk******@mkwah ler.net> wrote in message
news:P_******** *********@newsr ead1.news.pas.e arthlink.net...

"James A" <me@privacy.net > wrote in message
news:q6******** ******@newsfe2-gui.ntli.net...
Hi,

I'm having trouble geting my head around this, although I know it's a

pretty
basic question.

I have an application whereby an area of RAM is mapped to an array:

unsigned char NV[128];

Two consequtive elements are used to hold an unsigned int (2 bytes on this platform). How do I access it as an unsigned int?

e.g.
unsigned int test;
...
test = *(unsigned int *)(&(NV[15]);

In this case, I'm trying to retrieve the unsigned int value represented by elements 15 & 16 of the array. It does not seem to be working.

Could someone please explain what I'm doing wrong.


You don't give enough information. E.g.
How was the data originally stored?

#include <stdio.h>

int main()
{
unsigned char NV[128] = {0};
unsigned int test = 0;

NV[15] = NV[16] = 0xAA;
test = *(unsigned int *)(NV + 15);

printf("%u\n", test); /* prints 43690 for implementations with
*/
/* two-byte unsigned int and for 'little-endian'
*/
/* (e.g. most PC's) platforms with a larger
*/
/* unsigned int
*/

return 0;
}

-Mike


Many thanks Mike, Flash and Jens for your replies and advice.

Sorry for the lack of info. Here is hopefully what is needed:

By not working, I mean the unsigned int value stored is not the same value
returned later on.

Here is the code that should be storing the value:

unsigned int a, b;
...
*(unsigned int *)(&(NV[15])) = a;

The code that retreives the value later on in the code is this:

b = *(unsigned int *)(&(NV[15]));

[Apologies for the bracket error in the original post]

But in my testing, b does not equal a.

Debugging is somewhat tricky (the platform is a small embedded processor
[PIC12]) but the symptoms suggest that the most significant byte of the
unsigned int is being retrieved with the incorrect contents. The compiler
documentation says it uses little-endian format for its 16-bit unsigned
ints.

This problem might be down to me overwriting the area of the array concerned
elsewhere in the code. Could someone please say if the code above should
work ok. Then I can either eliminate it from my search, or go about fixing
it.

Thanks for all your help and patience!

James
Nov 14 '05 #5
James A <me@privacy.net > wrote:
By not working, I mean the unsigned int value stored is not the same value
returned later on. Here is the code that should be storing the value: unsigned int a, b;
...
*(unsigned int *)(&(NV[15])) = a; The code that retreives the value later on in the code is this: b = *(unsigned int *)(&(NV[15]));
That looks pretty good and should work (unless there are some align-
ment issues on your machine, but if this does not crashes the program
it should not be a problem). Actually, you could simplify that to

b = * ( unsigned int * ) ( NV + 15 );

etc., which I at least would find easier to read.
But in my testing, b does not equal a. Debugging is somewhat tricky (the platform is a small embedded processor
[PIC12]) but the symptoms suggest that the most significant byte of the
unsigned int is being retrieved with the incorrect contents.
Are you sure you're not writing to some hardware registers instead
of some simple memory? I just ask because you were writing about a
"memory range" and now about an "embedded processor" (which may use
memory mapped I/O) - so when there's some hardware register mapped
into that memory range and you accidentally hit one all bets are off,
of course...
The compiler documentation says it uses little-endian format for
its 16-bit unsigned ints.
If you compare what you have written yourself with what you read endian-
ness shouldn't be an issue here - it could be a problem if that would be
a buffer with some binary data you have received from a different machine.
This problem might be down to me overwriting the area of the array concerned
elsewhere in the code. Could someone please say if the code above should
work ok. Then I can either eliminate it from my search, or go about fixing
it.


I don't see why it shouldn't work. Checking if it does should be not too
difficult - write a short program that writes to a memory location this
way and read in what you have written immediately again. If this fails
something strange is going on (while I don't guess it will, one never
knows until one has tested it;-), otherwise it's a safe bet that some-
thing has overwritten the memory in between writing and reading.

If it does not work, you still can go the clean, portable road by
simply using memcpy(), i.e.

memcpy( NV + 15, &a, sizeof a );
...
memcpy( &b, NV + 15, sizeof b );

If this also fails you can be sure that either your memory is bad or
that it's not real memory at all.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #6
<Je***********@ physik.fu-berlin.de> wrote in message
news:2q******** *****@uni-berlin.de...
James A <me@privacy.net > wrote:
By not working, I mean the unsigned int value stored is not the same value returned later on.

Here is the code that should be storing the value:

unsigned int a, b;
...
*(unsigned int *)(&(NV[15])) = a;

The code that retreives the value later on in the code is this:

b = *(unsigned int *)(&(NV[15]));


That looks pretty good and should work (unless there are some align-
ment issues on your machine, but if this does not crashes the program
it should not be a problem). Actually, you could simplify that to

b = * ( unsigned int * ) ( NV + 15 );

etc., which I at least would find easier to read.
But in my testing, b does not equal a.

Debugging is somewhat tricky (the platform is a small embedded processor
[PIC12]) but the symptoms suggest that the most significant byte of the
unsigned int is being retrieved with the incorrect contents.


Are you sure you're not writing to some hardware registers instead
of some simple memory? I just ask because you were writing about a
"memory range" and now about an "embedded processor" (which may use
memory mapped I/O) - so when there's some hardware register mapped
into that memory range and you accidentally hit one all bets are off,
of course...
The compiler documentation says it uses little-endian format for
its 16-bit unsigned ints.


If you compare what you have written yourself with what you read endian-
ness shouldn't be an issue here - it could be a problem if that would be
a buffer with some binary data you have received from a different machine.
This problem might be down to me overwriting the area of the array concerned elsewhere in the code. Could someone please say if the code above should
work ok. Then I can either eliminate it from my search, or go about fixing it.


I don't see why it shouldn't work. Checking if it does should be not too
difficult - write a short program that writes to a memory location this
way and read in what you have written immediately again. If this fails
something strange is going on (while I don't guess it will, one never
knows until one has tested it;-), otherwise it's a safe bet that some-
thing has overwritten the memory in between writing and reading.

If it does not work, you still can go the clean, portable road by
simply using memcpy(), i.e.

memcpy( NV + 15, &a, sizeof a );
...
memcpy( &b, NV + 15, sizeof b );

If this also fails you can be sure that either your memory is bad or
that it's not real memory at all.
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de


Hi Jens,

Many thanks for your reply. I like your simplification of the code and will
switch to that - much more readable I agree! And thank you for confirming
that the code itself is not at fault - the problem must be somewhere else.

I didn't want to talk too much about the platform as I know this is a
generic C language group, so kept the details to a minimum. FWIW, the array
is declared using a qualifier that means it uses non-volatile memory in the
PIC - I use it to store various values that need to be retained across power
cycles. Unfortunately ROM space is incredibly tight so I had to switch from
discrete variables to a single, multi-purpose array in order to save a few
bytes in the compile size, and somewhere down the line this bug has crept
in.

Armed with your info and suggestions I should be able to track the problem
down soon.

Cheers,
James
Nov 14 '05 #7
On 17 Sep 2004 00:08:45 GMT
Je***********@p hysik.fu-berlin.de wrote:
James A <me@privacy.net > wrote:
By not working, I mean the unsigned int value stored is not the same
value returned later on.
Here is the code that should be storing the value:

unsigned int a, b;
...
*(unsigned int *)(&(NV[15])) = a;

The code that retreives the value later on in the code is this:

b = *(unsigned int *)(&(NV[15]));


That looks pretty good and should work (unless there are some align-
ment issues on your machine, but if this does not crashes the program
it should not be a problem). Actually, you could simplify that to


<snip>

Not true. The processor could just silently ignore the low bit of the
address or do something else even more screwy. Crashing is only the
nicest way it can fail.

<snip>
If it does not work, you still can go the clean, portable road by
simply using memcpy(), i.e.

memcpy( NV + 15, &a, sizeof a );
...
memcpy( &b, NV + 15, sizeof b );

If this also fails you can be sure that either your memory is bad or
that it's not real memory at all.


This is a very good suggestion.
--
Flash Gordon
Sometimes I think shooting would be far too good for some people.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #8

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

Similar topics

5
2416
by: Sandeep | last post by:
Hi, In the following code, I wonder how a private member of the class is being accessed. The code compiles well in Visual Studio 6.0. class Sample { private: int x; public:
4
4739
by: Steven T. Hatton | last post by:
I mistakenly set this to the comp.std.c++ a few days back. I don't believe it passed the moderator's veto - and I did not expect or desire anything different. But the question remains: ISO/IEC 14882:2003(E) §8.5 says:   To zero-initialize an object of type T means: 5   -- if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T;
27
4238
by: Daniel Lidström | last post by:
Hello! I want to work with individual bytes of integers. I know that ints are 32-bit and will always be. Sometimes I want to work with the entire 32-bits, and other times I want to modify just the first 8-bits for example. For me, I think it would be best if I can declare the 32-bits like this: unsigned char bits;
6
2746
by: Chris Styles | last post by:
Dear All, I've been using some code to verify form data quite happily, but i've recently changed the way my form is structured, and I can't get it to work now. Originally : The form is called "form1", and I have selects called "PORTA", "PORTB" ... etc...
2
1700
by: Greg Merideth | last post by:
Using Visual C# I created two forms such as namespace test { public class SystemTray : System.Windows.Forms.Form { public createwindow() { stuff here; } public fadewindow() { stuff to fade here; } public displaystuffinwindow() { display stuff here; } }
2
2650
by: Rafe Culpin | last post by:
Does anyone please know of a way to access static methods of a class, when the name of that class is held in a variable? I have several classes (PHP5) which all have identically named methods and members. I want to pass the name of one of the classes to an included file which does some standard operations using those methods and members. (So several different programs can include that file, each passing a different class name.)
7
3821
by: Chuck Anderson | last post by:
I'm pretty much a JavaScript novice. I'm good at learning by example and changing those examples to suit my needs. That said .... ..... I have some select fields in a form I created for a database search that I am unable to figure out how to access. (The search is implemented in Php/MySQL.) The user enters search values for: name, address1, city, .... etc., ..... and for each of these they also select whether the search should...
2
1606
by: agendum97 | last post by:
Is there a way of constructing a "class" in JavaScript to access a private member of a different scope of the same type? It is important that the variable remain private, and not accessible in anyway publically. For example: function SomeObj(privateKey) { this.process = function(someObj) { if (!(someObj instanceof SomeObj))
15
3773
by: bernd | last post by:
Hi folks, a simple question for the experts, I guess. Obviously I am doing something wrong when trying to access an element of an array declared within a structure: #include <stdio.h> #include <stddef.h>
0
9590
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
9424
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
10223
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
10051
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
10000
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,...
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.