473,769 Members | 3,557 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with structs and strings in C

Keep in mind my program is written in C ( not C++ ).

I have a function which takes two structs as parameters is supposed to
put the values of the source struct in the destination struct. Only
the first character is put into the destination struct for each field.
void AssignValues(in fo *source, info *destination)
{
*destination->name = *source->name;
*destination->class = *source->class;
*destination->alignment = *source->alignment;
}
Name, class and alignment are defined as
char variableName[20];
In a struct called info.

If my source is : test, TEST example
The destination is : t, T, e

Why is that ?

Thanks for your help.
Nov 14 '05 #1
7 1878
Bleakcabal <bl********@gdn mail.net> wrote:
Keep in mind my program is written in C ( not C++ ).

I have a function which takes two structs as parameters is supposed to
put the values of the source struct in the destination struct. Only
the first character is put into the destination struct for each field.


Use strcpy() or similar to copy strings.

Stig

--
brautaset.org
Nov 14 '05 #2
Bleakcabal wrote:

Keep in mind my program is written in C ( not C++ ).

I have a function which takes two structs as parameters is supposed to
put the values of the source struct in the destination struct. Only
the first character is put into the destination struct for each field.

void AssignValues(in fo *source, info *destination)
{
*destination->name = *source->name;
*destination->class = *source->class;
*destination->alignment = *source->alignment;
}

void AssignValues(in fo *source, info *destination)
{
*destination = *source;
}

--
pete
Nov 14 '05 #3
On 9 Feb 2004 05:12:27 -0800, bl********@gdnm ail.net (Bleakcabal)
wrote:
Keep in mind my program is written in C ( not C++ ).

I have a function which takes two structs as parameters is supposed to
put the values of the source struct in the destination struct. Only
the first character is put into the destination struct for each field.
void AssignValues(in fo *source, info *destination)
{
*destination->name = *source->name;
*destination->class = *source->class;
*destination->alignment = *source->alignment;
}
Name, class and alignment are defined as
char variableName[20];
In a struct called info.

If my source is : test, TEST example
The destination is : t, T, e

Why is that ?

A few solutions have been posted, and they're correct given your
context so far [just be careful: if you use strcpy, make sure the
source strings have been initialized properly; if you use structure
assignment, keep in mind that it will cease to work correctly if you
were to change the type of any of your data members from arrays to
pointers...and that may very well end up being your next step ;-) ]

Another hint: if code involving arrays or pointers doesn't work right,
carefully check the /types/ of the expressions involved. In this case,
all six main expressions are of the form:
* array
Remember that array names used in /most/ expressions "decay" to being
a pointer to their first element, so type-wise that equates to:
* (char *)
The *'s cancel leaving "char" as the type. Hence the char-to-char
assignment.

Rule of thumb: There's no single C assignment expression that can
directly copy an array (you'd have to cheat and embed the array in a
structure and copy the structure, which is why Pete's solution works
so nicely in this case.)
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #4
Hi Pete,
this seems to be similar to a
question I posted earlier. But
won't
*destination = *source;


just copy the adresses of the array,
s.th like a non-deep copy? So both
structs share the strings?
Kind Regards,
Michael

Nov 14 '05 #5
On Mon, 09 Feb 2004 15:49:13 +0100, Michael <mi****@gmx.net > wrote:
Hi Pete,
this seems to be similar to a
question I posted earlier. But
won't
*destination = *source;


just copy the adresses of the array,
s.th like a non-deep copy? So both
structs share the strings?


Nope, there's no problem here because we're copying values, not
addresses. If the data members of the structure were pointers, /then/
we'd be copying addresses and inviting all sorts of undefined behavior
down the road when the program begins freeing them (or at least chaos
before that if the program expects the data being pointed to by the
two separate pointers to be distinct.)
-leor

Leor Zolman
BD Software
le**@bdsoft.com
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #6
Michael wrote:

this seems to be similar to a
question I posted earlier. But
won't
*destination = *source;


just copy the adresses of the array,
s.th like a non-deep copy? So both
structs share the strings?


You removed context quotations, including all definitions. IIR
you defined the fields within the structures as arrays, not as
pointers, so there is nothing deep to copy.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #7


CBFalconer wrote:
Michael wrote:
this seems to be similar to a
question I posted earlier. But
won't

*destination = *source;


just copy the adresses of the array,
s.th like a non-deep copy? So both
structs share the strings?

You removed context quotations, including all definitions. IIR
you defined the fields within the structures as arrays, not as
pointers, so there is nothing deep to copy.


The op definitions are a little unclear. There is some evidence
that the members are typedef char array of 20 characters. If this
is the case, struct assignment will be safe as will using function
strcpy.

Example:

#include <stdio.h>
#include <string.h>

typedef char variableName[20];
typedef struct info
{
variableName name;
variableName class;
variableName alignment;
}info;

info init = {"No data","No data", "No data"};

void AssignValues1(c onst info *source, info *destination)
{
*destination = *source;
}

void AssignValues2(c onst info *source, info *destination)
{
strcpy(destinat ion->name,source->name);
strcpy(destinat ion->class, source->class);
strcpy(destinat ion->alignment,sour ce->alignment);
return;
}

void PrintInfo(const info *p)
{
char *s = "No Data";
printf("Name: %s\nClass: %s\nAlignment: %s\n\n",
p->name,p->class,p->alignment);
}

int main(void)
{
info myinfo = {"George Washington","Po litical Science","Junio r"};
info newinfo = init;

puts("struct newinfo contents");
PrintInfo(&newi nfo);

newinfo = myinfo;
puts("Using simple assignment");
PrintInfo(&newi nfo);
newinfo = init;

puts("Using function AssignValues1") ;
AssignValues1(& myinfo, &newinfo);
PrintInfo(&newi nfo);
newinfo = init;

puts("Using function AssignValues2") ;
AssignValues2(& myinfo, &newinfo);
PrintInfo(&newi nfo);

return 0;
}
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #8

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

Similar topics

8
2146
by: Oliver Gerlich | last post by:
Hello, I want to transfer messages between a client and a server (over TCP sockets). A message consists of a message type (like a message "subject" :), the size of the attached data, and the data itself. The data part should then be able to contain some information whose layout depends on the message type... So now I thought I could define some structs which represent the layout of the additional information, like this: typedef struct
6
2969
by: Simon Elliott | last post by:
I have ome new code which has to work with some legacy code which does a lot of memset's and memcmp's on structs of PODs. This leads me to want to do stuff like this: struct foo { unsigned char c1_; unsigned short us1_; };
7
1317
by: Jeff Mott | last post by:
Ok, here's the situation. I've got a file whose first line indicates how many n number of names will follow. And some more data after that, but I havn't gotten that far yet. So what I've got is... 1: #include <stdio.h> 2: #include <stdlib.h> 3: 4: typedef struct { 5: char* name; 6: int initial_money_value;
4
6023
by: ccdrbrg | last post by:
I am trying to initialize an arrary of pointers to structs with constants. Sample code: struct mystruct { char *text; int number; };
9
1955
by: Alfonso Morra | last post by:
Hi, I am having some probs with copying memory blocks around (part of a messaging library) and I would like some confirmation to make sure that I'm going about things the right way. I have some data types defined thus: typedef enum { ONE ,
5
348
by: sherifffruitfly | last post by:
Hi, I'm just learning cpp, and the exercise I'm working on is basically as follows: 1) Create a struct type with 4 members (char, char, char, int). 2) Create an array of, say 3 instances of the struct, and populate them with data. 3) cin 1, 2, 3, or 4 from the user 4) If the user selected, say, 2, display the contents of the 2nd data
50
20328
by: titan nyquist | last post by:
I wish to compare two structs via == but it does not compile. I can overload and create my own == but am I missing something that c# already has implemented? ~titan
3
1924
by: mearvk | last post by:
I am unable to get Xerces to write out attributes from a struct which I am able to print out and verify is correct. The structs are defined below as is subsection of the output. int DDAS_XML_Handler::writeResultDocument( int job_id, int num_results, DDAS_CLIENT_RESULT_DATA* results )
24
3318
by: Alexander Mahone | last post by:
Hello, I'm looking for an hash function to be used for an hash table that will contain structs of a certain kind. I've looked into Sourceforge.net, but so far I've found only hash functions for strings (string->index)...Do you know if there exist such a function somewhere? Thanks
0
9422
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
10206
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
9984
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
8863
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...
1
7403
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
5293
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
5441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3949
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
3
2811
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.