473,765 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The size of a char array

I have this structure:

struct some
{
int version;
char signature[3];
} some2

void main()
{
some2.version = 1;
strcpy(some2, "ihs");
}

the question is:
The signature member length is 3, but when i copy the "ihs" string to
it, the data is "ihs\0"; If i save this structure to disk, this member
will get 4 bytes. How can i avoid this ??? Thanks.

Nov 14 '05 #1
7 2594
In article <11************ **********@f14g 2000cwb.googleg roups.com>,
=?iso-8859-1?q?Luiz_Antoni o_Gomes_Pican=E 7o?= <lu**@luizanton io.com> wrote:
:I have this structure:

:struct some
:{
: int version;
: char signature[3];
:} some2

: strcpy(some2, "ihs");

First off, you don't want to strcpy over the whole structure, just over
the signature part of it, some2.signature

:The signature member length is 3, but when i copy the "ihs" string to
:it, the data is "ihs\0"; If i save this structure to disk, this member
:will get 4 bytes. How can i avoid this ??? Thanks.

Secondly, when you have a restricted field width, you should use
something like:

strncpy( some2.signature , "ihs", 3 );

Thirdly, the member is apparently getting 4 bytes because of
padding. There is no portable way in C to force a structure
to be unpadded (sometimes called 'packed'). If you need to store
something without padding, then you need to create a byte array
(i.e., unsigned char array) and copy the elements into place
manually:

#define some_size (sizeof(some.ve rsion) + sizeof(some.sig nature))
typedef char some_as_array_t[some_size];

void dosomething(voi d) {
some_as_array someArr;
strncpy( someArr, (char*)&some.ve rsion, sizeof(some.ver sion) );
strncpy( someArr + sizeof(some.ver sion), some.signature,
sizeof(some.sig nature) ];
fwrite( someArr, some_size, 1, OutFile );

....
some_as_array someInArr;
fread( someInArr, some_size, 1, InFile );
strncpy( (char *)&someIn.versi on, someInArr, sizeof( someIn.version) );
strncpy( someIn.signatur e, someInArr + sizeof(someIn.v ersion),
sizeof(someIn.s ignature) );
ver = sommeIn.version ;
stnrcpy( sig, someIn.signatur e, sizeof(someIn.s ignature) );
}
--
"I want to make sure [a user] can't get through ... an online
experience without hitting a Microsoft ad"
-- Steve Ballmer [Microsoft Chief Executive]
Nov 14 '05 #2
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizanton io.com> wrote:
I have this structure:

struct some
{
int version;
char signature[3];
} some2

void main()
{
some2.version = 1;
strcpy(some2, "ihs");
}
Did you mean strcpy(some2.si gnature, "ihs") ?
the question is:
The signature member length is 3, but when i copy the "ihs" string to
it, the data is "ihs\0"; If i save this structure to disk, this member
will get 4 bytes. How can i avoid this ??? Thanks.


The extra byte is not going in your structure, but writing past it in
memory. Don't do that - the results are unpredictable. Look into using
strncpy, or even memcpy.

If you write the structure to disk, it should write only sizeof(int) +
3 bytes.

--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #3
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) writes:
[...]
Secondly, when you have a restricted field width, you should use
something like:

strncpy( some2.signature , "ihs", 3 );


Be careful with strncpy; it can leave you with an unterminated string.
(Actually not a string at all, but a character array with no trailing
'\0'.) That's ok as long as you're treating it as an array of
characters, but if you use a string function on it you'll get
undefined behavior.

--
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.
Nov 14 '05 #4
Alan Balmer <al******@att.n et> writes:
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizanton io.com> wrote:
I have this structure:

struct some
{
int version;
char signature[3];
} some2

void main()
{
some2.version = 1;
strcpy(some2, "ihs");
}
[snip] If you write the structure to disk, it should write only sizeof(int) +
3 bytes.


The size of the structure is sizeof(struct some), which may or may not
be sizeof(int)+3. (In fact, it's very likely that there will be at
least one byte of padding at the end of the structure.)

You can read and write raw struct values to files, but don't expect
them to be readable from a program on another system, or compiled with
another compiler, or even necessarily with another version of the same
compiler.

And main() returns int, not void.

--
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.
Nov 14 '05 #5
In article <ln************ @nuthaus.mib.or g>,
Keith Thompson <ks***@mib.or g> wrote:
:ro******@ibd.n rc-cnrc.gc.ca (Walter Roberson) writes:
:> Secondly, when you have a restricted field width, you should use
:> something like:

:> strncpy( some2.signature , "ihs", 3 );

:Be careful with strncpy; it can leave you with an unterminated string.

Sure can -- but seeing as the OP wants to write "ihs" into a field
that only holds three characters, all the alternatives are at least
as bad.
--
Would you buy a used bit from this man??
Nov 14 '05 #6
On Tue, 08 Mar 2005 20:46:46 GMT, Keith Thompson <ks***@mib.or g>
wrote:
Alan Balmer <al******@att.n et> writes:
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizanton io.com> wrote:
I have this structure:

struct some
{
int version;
char signature[3];
} some2

void main()
{
some2.version = 1;
strcpy(some2, "ihs");
}
[snip]
If you write the structure to disk, it should write only sizeof(int) +
3 bytes.


The size of the structure is sizeof(struct some), which may or may not
be sizeof(int)+3. (In fact, it's very likely that there will be at
least one byte of padding at the end of the structure.)


But not guaranteed, of course. I should have been clearer. As you say,
at least one byte of padding is likely, but should not be counted on,
or even thought about ;-)
You can read and write raw struct values to files, but don't expect
them to be readable from a program on another system, or compiled with
another compiler, or even necessarily with another version of the same
compiler.
Yes. There are various solutions to this problem. The cleanest
portable one is to turn all values into text, with specified
delimiters.
And main() returns int, not void.


--
Al Balmer
Balmer Consulting
re************* ***********@att .net
Nov 14 '05 #7


Alan Balmer wrote:
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizanton io.com> wrote:

I have this structure:

struct some
{
int version;
char signature[3];
} some2

[...]
If you write the structure to disk, it should write only sizeof(int) +
3 bytes.


It's unlikely but possible that there could be
padding between the `version' and `signature' elements,
so writing sizeof(int)+3 bytes wouldn't necessarily
write all the "payload" data. For bullet-proof code,
either write the two elements separately

fwrite (&some2.version , sizeof some2.version, 1, stream);
fwrite (some2.signatur e, sizeof some2.signature , 1, stream);

or else assemble them into a "packed" array and write that:

char buff[sizeof some2.version + sizeof some2.signature];
memcpy (buff, &some2.versi on, sizeof some2.version);
memcpy (buff + sizeof some2.version,
some2.signature , sizeof some2.signature );
fwrite (buff, sizeof buff, 1, stream);

If the O.P. is trying to match an externally-imposed
format, he may also need to worry about other issues: the
fact that sizeof some2.version can differ from machine to
machine, endianness problems, and so on.

--
Er*********@sun .com

Nov 14 '05 #8

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

Similar topics

14
3914
by: Gianni Mariani | last post by:
Does anyone know if this is supposed to work ? template <unsigned N> int strn( const char str ) { return N; } #include <iostream>
4
6401
by: Angus Comber | last post by:
Hello If I do this: struct mystruct { long nKey; char szItem; };
4
2813
by: terry | last post by:
Hi, Could anyone tell me how to determine the size of array of characters dynamically? For example, : : char *a={"hello","hi","kitty"}; char *b={"orange","apple"};
6
2309
by: dddddddd2444444 | last post by:
Hi,please help... It works fine when I define a 2-D array like char code. But it won't work when I try to define the array dynamically using a function. It just crashes. Does anyone know why? The compiler i'm using is Dev c++. #include <stdio.h> #include <stdlib.h>
7
5639
by: arkobose | last post by:
hey everyone! i have this little problem. consider the following declaration: char *array = {"wilson", "string of any size", "etc", "input"}; this is a common data structure used to store strings of any lengths into an array of pointers to char type variable. my problem is: given the declaration
5
2125
by: eagle_jyjh | last post by:
For example: the msg = temp_buf; is alwawys ok? //test_msg.cpp struct msg_head { char a01;
2
2408
by: Harry | last post by:
Good Day To all, When i am declaring a array for e.g char ....it means i am declaring array of 45 characters each of which has a maximum,minimum value limit or range...for example in VC++(compiler that i am using,it has nothing to do with C++) char's range is -128 to +127....this is the range for each char element..... My doubt is what is the upper limit for the array size(45 is the size here) and what decides it.....
15
6558
by: subramanian100in | last post by:
Is it possible to measure the size of an array without using the sizeof operator ?
7
4512
by: daniel | last post by:
Hello , I always had the feeling that is better to have char arrays with the size equal to a power of two. For example: char a_str; // feels ok char b_str; //feels not ok.
8
2448
by: s4tanu | last post by:
Hi, char arr_one = {'a','b','c','d','\0'}; i want to make another array with same size as 'arr_one' if i do like this - size_t len= strlen(arr); char arr_two;
0
9398
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
10156
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
9951
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
9832
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
5275
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
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
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.