473,387 Members | 1,481 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 2570
In article <11**********************@f14g2000cwb.googlegroups .com>,
=?iso-8859-1?q?Luiz_Antonio_Gomes_Pican=E7o?= <lu**@luizantonio.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.version) + sizeof(some.signature))
typedef char some_as_array_t[some_size];

void dosomething(void) {
some_as_array someArr;
strncpy( someArr, (char*)&some.version, sizeof(some.version) );
strncpy( someArr + sizeof(some.version), some.signature,
sizeof(some.signature) ];
fwrite( someArr, some_size, 1, OutFile );

....
some_as_array someInArr;
fread( someInArr, some_size, 1, InFile );
strncpy( (char *)&someIn.version, someInArr, sizeof( someIn.version));
strncpy( someIn.signature, someInArr + sizeof(someIn.version),
sizeof(someIn.signature) );
ver = sommeIn.version;
stnrcpy( sig, someIn.signature, sizeof(someIn.signature) );
}
--
"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**@luizantonio.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.signature, "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.nrc-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_Keith) 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.net> writes:
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizantonio.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_Keith) 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.org>,
Keith Thompson <ks***@mib.org> wrote:
:ro******@ibd.nrc-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.org>
wrote:
Alan Balmer <al******@att.net> writes:
On 8 Mar 2005 12:01:49 -0800, "Luiz Antonio Gomes Picanço"
<lu**@luizantonio.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**@luizantonio.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.signature, 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.version, 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
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
by: Angus Comber | last post by:
Hello If I do this: struct mystruct { long nKey; char szItem; };
4
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
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?...
7
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...
5
by: eagle_jyjh | last post by:
For example: the msg = temp_buf; is alwawys ok? //test_msg.cpp struct msg_head { char a01;
2
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...
15
by: subramanian100in | last post by:
Is it possible to measure the size of an array without using the sizeof operator ?
7
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
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
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
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...

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.