473,883 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Querry aoubt struct including character strings pointer

Hello, all.
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c

#include <stdio.h>
#define LEN 20

struct info {
char first[LEN];
char last[LEN];
int age;
};

struct pinfo {
char * first;
char * last;
int age;
};

int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}

//end test1.c

It can work.I know a little,but not very detail that the second struct pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.

The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?

Thank you.

bowderyu

Oct 20 '08 #1
19 2073
bowlderyu wrote:
Hello, all.
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c

#include <stdio.h>
#define LEN 20

struct info {
char first[LEN];
char last[LEN];
int age;
};

struct pinfo {
char * first;
char * last;
int age;
};

int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}

//end test1.c

It can work.I know a little,but not very detail that the second struct pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
It will work fine.

The answer to your question depends on your definition of "not good".
The first form is OK if you want mutable strings with a known maximum
length. The second is OK if you want constant strings and would be
safer if changed to

struct pinfo {
const char * first;
const char * last;
int age;
};
The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Which problem are you trying to avoid?

--
Ian Collins
Oct 20 '08 #2
Ian Collins <ia******@hotma il.comwrites:
const char *, good sugesstion.

I don't know why it can not work for the case of two[1], so I want to
avoid using char array. But now, it seems fine.

Would you please give more explanation about it?
I mean for why not safe for non-constant strings.

I am thinking about, seems clearly.

Now, I have to leave.

Anyway, thank you .
bowlderyu wrote:
>Hello, all.
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c

#include <stdio.h>
#define LEN 20

struct info {
char first[LEN];
char last[LEN];
int age;
};

struct pinfo {
char * first;
char * last;
int age;
};

int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}

//end test1.c

It can work.I know a little,but not very detail that the second struct pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
It will work fine.

The answer to your question depends on your definition of "not good".
The first form is OK if you want mutable strings with a known maximum
length. The second is OK if you want constant strings and would be
safer if changed to

struct pinfo {
const char * first;
const char * last;
int age;
};
>The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Which problem are you trying to avoid?
Oct 20 '08 #3
bowlderyu wrote:
Hello, all.
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c

#include <stdio.h>
#define LEN 20

struct info {
char first[LEN];
char last[LEN];
int age;
};

struct pinfo {
char * first;
char * last;
int age;
};

int main(void)
{
struct info one = {"Opw", "Cde", 22};
In this case, you are creating arrays whose contents can be safely
modified, which are stored as part of 'one'.
struct pinfo two = {"Tydu", "Gqa", 33};
In this case, you are creating two unnamed arrays, whose contents cannot
be safely modified. You are storing pointers to those arrays in 'two'.
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}

//end test1.c

It can work.I know a little,but not very detail that the second struct pinfo is not good
There's no reason why it shouldn't be.
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
If you change how you declare "two":

struct pinfo two[1] = {"Tydu", "Gqa", 33};

Then you also have to change how you use "two":

printf("%s %s is %d years old.\n",
two[0].first, two[0].last, two[0].age);

Assuming you made matching changes, as above, there's no reason why it
shouldn't work. Arrays of length 1 are generally pointless, but they're
perfectly legal.
The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Better in what sense? It's a lot more complicated than either method
you've shown above. I'd use the first method if the strings need to be
writable, but have a small fixed maximum length. I'd use the second
method if the strings don't need to be writable, though I would change
first and last to be "const char*" rather than "char*".

The only time I would ever use the malloc() approach is if the length of
the strings was not known at compile time, and has a large upper limit.
Oct 21 '08 #4
please put your reply after the text you are replying to.
Putting it before (as you did) is called "top posting".
I have rearranged your post.

On 21 Oct, 00:52, bowlderyu <bowlde...@gmai l.comwrote:
Ian Collins <ian-n...@hotmail.co mwrites:
bowlderyu wrote:
If a struct contains a character strings, there are two methods to
define the struct, one by character array, another by character pointer.
E.g,
//Program for struct includeing character strings, test1.c
#include <stdio.h>
#define LEN 20
struct info {
char first[LEN];
char last[LEN];
int age;
};
struct pinfo {
char * first;
char * last;
int age;
};
int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};
printf("%s %s is %d years old.\n", one.first, one.last, one.age);
printf("%s %s is %d years old.\n", two.first, two.last, two.age);
return 0;
}
//end test1.c
It can work.I know a little,but not very detail that the second struct
pinfo is not good
in the above code. E.g, if the struct pinfo two is defined as an array
two[1] in the main function, it can not work. I just want to know the
reason in detail.
It will work fine.
The answer to your question depends on your definition of "not good".
The first form is OK if you want mutable strings with a known maximum
length. The second is OK if you want constant strings and would be
safer if changed to
struct pinfo {
const char * first;
const char * last;
int age;
};
The better way to avoid this problem is malloc() and another pointer
point to the struct, and copy the strings, then free it. Is it right?
Which problem are you trying to avoid

const char *, good sugesstion.

I don't know why it can not work for the case of two[1], so I want to
avoid using char array. But now, it seems fine.

Would you please give more explanation about it?
I mean for why not safe for non-constant strings.
consider this:=

#include <stdio.h>
#define LEN 20

struct info {
char first[LEN];
char last[LEN];
int age;
};

struct pinfo {
char * first;
char * last;
int age;
};

int main(void)
{
struct info one = {"Opw", "Cde", 22};
struct pinfo two = {"Tydu", "Gqa", 33};

/* this is ok */
one.first[0] = 'X';

/* this is NOT ok! */
two.first[0] = 'X';

return 0;
}

one contains modifiable arrays. So its ok to modify them.
two points to string constants so it is *not* ok to modify
them. You cannot modify string constants.

This is ok:

int main(void)
{
struct pinfo two;
char first_arr[5] = "Tydu";

two.first = first_arr;
two.first[0] = 'X';

return 0;
}
I do not understand what you mean when you say "I don't know why it
can not work for the case of two[1], so I want to avoid using char
array. But now, it seems fine.".

Could you give an example which believe may be a problem.

I am thinking about, seems clearly.

--
Nick Keighley

1,3,7-trimethylxanthi ne -- a basic ingredient in quality software.
Oct 21 '08 #5
Nick Keighley said:

<snip>
You cannot modify string constants.
s/cannot/must not/

This, as Nick already knows, is one of those situations where the C
language places a demand on the programmer rather than on the
implementation. Complying with that demand is, therefore, a matter of
self-discipline rather than implementation-imposed discipline. When
programmers ignore such demands, very often they get away with it. But
sometimes, they don't.

It's almost like driving on the wrong side of the road. If you live in a
relatively traffic-free area, you can actually drive on the wrong side of
the road for quite extended periods - but you only have yourself to blame
when you wrap yourself round a Mini Metro, with quite possibly fatal
consequences.

(It's not *quite* the same, because the police will enforce the law if they
happen to spot you. If you live anywhere near me, the chances of that are
pretty low, since the bobbies around here seem utterly incapable of
distinguishing their seating arrangements from their arm joints.
Nevertheless, the point stands.)

<snip>

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 21 '08 #6
Richard Heathfield wrote:
Nick Keighley said:

<snip>
>You cannot modify string constants.

s/cannot/must not/

This, as Nick already knows, is one of those situations where the C
language places a demand on the programmer rather than on the
implementation. Complying with that demand is, therefore, a matter of
self-discipline rather than implementation-imposed discipline. When
programmers ignore such demands, very often they get away with it. But
sometimes, they don't.

It's almost like driving on the wrong side of the road. If you live
in a relatively traffic-free area, you can actually drive on the
wrong side of the road for quite extended periods - but you only have
yourself to blame when you wrap yourself round a Mini Metro, with
quite possibly fatal consequences.
Happened to me once in the UK, driving on the right side (as opposed to
left, not wrong, but to me that's the same thing 8-)), for several miles on
an empty road in the very early hours of a day. Until a lorry approaching me
on my side stopped me... fortunatly no fatalities, not even a crash.
(It's not *quite* the same, because the police will enforce the law
if they happen to spot you. If you live anywhere near me, the chances
of that are pretty low, since the bobbies around here seem utterly
incapable of distinguishing their seating arrangements from their arm
joints. Nevertheless, the point stands.)
Some pedestrians were staring at me, but indeed no bobbies in sight...

Bye, Jojo
Oct 21 '08 #7
Joachim Schmitz wrote:
>
.... snip ...
>
Happened to me once in the UK, driving on the right side (as
opposed to left, not wrong, but to me that's the same thing 8-)),
for several miles on an empty road in the very early hours of a
day. Until a lorry approaching me on my side stopped me...
fortunatly no fatalities, not even a crash.
Way back when Sweden still drove on the left I visited there, and
the UK. I deliberately didn't take up any opportunities to drive,
because I expected habit would be over-riding. Even so, the London
traffic made mighty efforts to get me, as I looked left, saw no
traffic, and stepped out from the curb to be bashed from the right.

In Germany, France, Italy, Austria I could take a different
attitude. I did have problems with the German method of driving a
DKW, with a pure toggle action on the throttle.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Oct 21 '08 #8
CBFalconer wrote:
Joachim Schmitz wrote:
>>
... snip ...
>>
Happened to me once in the UK, driving on the right side (as
opposed to left, not wrong, but to me that's the same thing 8-)),
for several miles on an empty road in the very early hours of a
day. Until a lorry approaching me on my side stopped me...
fortunatly no fatalities, not even a crash.

Way back when Sweden still drove on the left I visited there, and
the UK. I deliberately didn't take up any opportunities to drive,
because I expected habit would be over-riding. Even so, the London
traffic made mighty efforts to get me, as I looked left, saw no
traffic, and stepped out from the curb to be bashed from the right.
Been there, done that... on a dual carriageway (amongst others), thanks to a
great reaction of the driver I survived.
In Germany, France, Italy, Austria I could take a different
attitude. I did have problems with the German method of driving a
DKW, with a pure toggle action on the throttle.
Guess I'm to young for this, although I do recognize the brand name.

Bye, Jojo
Oct 22 '08 #9
Moi
On Wed, 22 Oct 2008 09:06:49 +0200, Joachim Schmitz wrote:
CBFalconer wrote:
>In Germany, France, Italy, Austria I could take a different attitude.
I did have problems with the German method of driving a DKW, with a
pure toggle action on the throttle.

Guess I'm to young for this, although I do recognize the brand name.

Bye, Jojo
DKW used to be a brand of LKW.

But that was long before K&R.
:-)
AvK
Oct 22 '08 #10

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

Similar topics

6
5443
by: Stuart Norris | last post by:
Dear Readers, I am attempting to initialise a struct contiaing a dynamic character string. In the example below I am trying to initialise the name field so that my struct does not waste space. I know if I change char name this will work, but I will waste alot of space. (I am learning so I want to learn the best way) How can I define a struct the allows variable length character strings in the
13
83917
by: mike79 | last post by:
hi all.. if I wanted to malloc a struct, say the following: struct myStruct1 { int number; char *string; }
67
10780
by: S.Tobias | last post by:
I would like to check if I understand the following excerpt correctly: 6.2.5#26 (Types): All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Does it mean that *all* structure (or union) types have the same alignment? Eg. type
14
4704
by: indigodfw | last post by:
Greetings from India I would like to know the rationale on allowing structs to be assigned (using = operator) and not allowing equality operator ( == operator) on them. The compiler when it assigns using = is aware of holes etc and the same compiler then should be able to generate code to compare the individual struct fields.
16
1583
by: Zero | last post by:
Hi everybody! I have the following code: struct Infos { char Haarfarbe; int Groesse; }; struct Person
4
2209
by: taskswap | last post by:
I'm converting an application that relies heavily on a binary network protocol. Within this protocol are a lot of byte arrays of character data, like: public unsafe struct MsgAddEntry { public byte MsgType; public uint Tag; public fixed byte ID; public fixed byte Val1;
2
3700
by: Tiger | last post by:
I try to write a struct into a brut file but I can't write all var in this struct when I try to add user I have that : > testmachine:/usr/share/my_passwd# ./my_passwd -a users.db > Ajout d'une entrée dans la base : > > Username : test > Password : aze > Gecos : qsd
14
4106
by: Shhnwz.a | last post by:
Hi, I am in confusion regarding jargons. When it is technically correct to say.. String or Character Array.in c. just give me your perspectives in this issue. Thanx in Advance.
1
1755
Steve Kiss
by: Steve Kiss | last post by:
Hi. I am developping a site for which one of the pages uses querry strings to pass some parameters. I can use the querry strings if I call the page from a plain html anchor. However, when I add the URL to the sitemap I get the following error: The 'url' property had a malformed URL This is the offending URL: ViewImages.aspx?area=M3000Gallery&areaName=Merlin%203000%20Press%20Brake%20Guarding I also tried:...
0
9933
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
9779
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
10730
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...
0
10407
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
9563
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
5787
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
5982
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4605
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
4205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.