473,779 Members | 2,092 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Character Points/Structs/Input

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_v alue;
7: int current_money_v alue;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in ", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc (n_people, sizeof(person)) ;
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people[i].name);
24: people[i].current_money_ value = 0;
25: }
26: }

Unfortunately the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...

21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people[i].name = nm;
26: people[i].current_money_ value = 0;
27: }

Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?

Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.
Nov 14 '05 #1
7 1317
Jeff Mott wrote:

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_v alue;
7: int current_money_v alue;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in ", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc (n_people, sizeof(person)) ;
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people[i].name);
24: people[i].current_money_ value = 0;
25: }
26: }

Unfortunately the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...

21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people[i].name = nm;
26: people[i].current_money_ value = 0;
27: }

Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?
This is Question 7.1 in the comp.lang.c Frequently Asked
Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html
Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.


One highly recommended practice is to read the FAQ and to
ponder carefully any answers you find surprising or confusing.
It also has a bibliography, slightly dated perhaps but still a
good place to start.

--
Er*********@sun .com
Nov 14 '05 #2
Jeff Mott wrote:
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_v alue;
7: int current_money_v alue;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in ", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc (n_people, sizeof(person)) ;
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people[i].name);
24: people[i].current_money_ value = 0;
25: }
26: }

Unfortunately the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...

21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people[i].name = nm;
26: people[i].current_money_ value = 0;
27: }

Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?

Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.


Hi Jeff, I didn't try to compile you program because of the line
numbering. A cursory look at it seems that the various person.name
pointers are never initialized to point to memory.

--
Joe Wright mailto:jo****** **@comcast.net
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 14 '05 #3
*** post for FREE via your newsreader at post.newsfeed.c om ***

mj****@twcny.rr .com (Jeff Mott) wrote in
news:97******** *************** ***@posting.goo gle.com:

[...]
10: person* people;
[...]
26: people[i].current_money_ value = 0;
27: }

[...]

Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.


Can you see the difference here?

a)

struct
{
int b;
char c;
}
a;

/* ... */
a.b = 42;
a.c = 'H';

b)

struct
{
int b;
char c;
}
*a;

/* ... */
a = malloc (sizeof *a);
/* assuming success */
a -> b = 42;
a -> c = 'H';
free (a); /* let it go, of course */

If you can find the inconsistency between a) and b), you'll have it.

This is not a programming practice, but a posting one: Don't include line
numbers. While they make it easier to identify problem lines, their
inclusion renders a posted program uncompilable. I personally wouldn't make
the effort to remove all those numbers to find out what my compiler would
tell me about this program.

Andrew
-----= Posted via Newsfeed.Com, Uncensored Usenet News =-----
http://www.newsfeed.com - The #1 Newsgroup Service in the World!
-----== 100,000 Groups! - 19 Servers! - Unlimited Download! =-----

Nov 14 '05 #4
On 2 Apr 2004 14:00:03 -0800, mj****@twcny.rr .com (Jeff Mott) wrote:
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_v alue;
7: int current_money_v alue;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in ", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc (n_people, sizeof(person)) ;
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people[i].name);
24: people[i].current_money_ value = 0;
25: }
26: }

Unfortunatel y the program will crash at runtime, apparently at line
23. However, if I replace that last block of code with...
As well it should. You never initialize people[i].name to point to
valid memory. Passing the value of an uninitialized variable to a
function invokes undefined behavior. (Any attempt to evaluate an
uninitialized variable does so.) If that isn't bad enough, fscanf
will try to store something in the memory .name points to. Since it
doesn't point to memory you own (it doesn't point anywhere, it's value
is indeterminate), this also invokes undefined behavior.

21: int i = 0;
22: char* nm;
23: for ( ; i < n_people; ++i) {
24: fscanf(in, "%s", nm);
25: people[i].name = nm;
26: people[i].current_money_ value = 0;
27: }

Then this will work. So apparently there is some detail about either
strings or structs (or something related) that I'm missing. Why does
the first version crash?
How does this improve the situation? You have substituted one
uninitialized pointer (nm) for another (.name). What you have is an
excellent example of why undefined behavior cannot be depended on to
behave in any predictable way. The first behavior is obviously more
user friendly since it informs you immediately that there is a
problem. The second is rather insidious because it leads you to
believe your code is correct when in fact it is just as broken.

Also, since I'm learning the language, if there are any good
programming practices that I have not followed, please alert me to
these as well.


Get rid of the line numbers when posting. People who are willing to
help (by compiling your code) don't need the extra work of removing
them.

It is OK to define an uninitialized variable (style debate aside) but
you must make sure that the variable is assigned a value before it is
referenced/evaluated.
<<Remove the del for email>>
Nov 14 '05 #5
Jeff Mott wrote:
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_v alue;
7: int current_money_v alue;
8: } person;
9:
10: person* people;
11:
12: int main(void)
13: {
14: FILE* in = fopen("gift1.in ", "r");
15:
16: int n_people;
17: fscanf(in, "%i", &n_people);
18:
19: people = (person*)calloc (n_people, sizeof(person)) ;
20:
21: int i = 0;
22: for ( ; i < n_people; ++i) {
23: fscanf(in, "%s", people[i].name);

^^^^^^^^^^^^^^^
You haven't allocated any space to which the pointer people[i].name
should point. Read the name into a buffer of an appropriately large
size (fgets is a better idea that fscanf, especially with that "%s"
specifier), find the length of the string, allocate space one larger
than that for people[i].name, and copy the string to that space.

Nov 14 '05 #6
Alright, thanks everybody. I realized my misconception now.
Nov 14 '05 #7
Alright, thanks everybody. I realized my misconception now.
Nov 14 '05 #8

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

Similar topics

1
1254
by: Gregory W. Ernest | last post by:
I am writing a c++ program for one of my classes. One of the assignments I had was to create a program that would bascially calculate the number of points in a game of Bridge using the principles of Object orientied programming. The input is a stream of characters which represent the value and suit of the card. For example, as would represent ace of spades, 2d would be two of diamonds etc. To handle that I have created four arrays of...
6
249
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;
2
2593
by: mazsx | last post by:
Is there a portable way to use binary files? By portability I mean: Machine A (a supercomputer) with some compiler, my job runs there and outputs several megabytes of data. To save space and for better seekability, I use a binary format. Machine B (my desktop) with some other compiler analizes this data. So far I assumed that both architectures have the standard representation of the float, double and int types. I would like to use now...
1
4575
by: sonald | last post by:
Dear All, I am working on a module that validates the provided CSV data in a text format, which must be in a predefined format. We check for the : 1. Number of fields provided in the text file, 2. Text checks for max. length of the field & whether the field is mandatory or optional Example:
44
9499
by: Kulgan | last post by:
Hi I am struggling to find definitive information on how IE 5.5, 6 and 7 handle character input (I am happy with the display of text). I have two main questions: 1. Does IE automaticall convert text input in HTML forms from the
25
5445
by: ehabaziz2001 | last post by:
Why I can not begin my subscript of character arrrays with 0. In this program I can not do : do { na=getchar(); i++; na=getchar(); } while (na!='\n');
17
10709
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, Wide character and multi-byte character are two popular encoding schemes on Windows. And wide character is using unicode encoding scheme. But each time I feel confused when talking with another team -- codepage -- at the same time. I am more confused when I saw sometimes we need codepage parameter for wide character conversion, and sometimes we do not need for conversion. Here are two examples,
1
1558
by: kimt | last post by:
Hello, I am currently writing an application that involves many (> 1000) points on a (x,y) plane. I am using a struct to contain the position information, and I have the structs contained in a STL vector. Given a target coordinate (x,y)_t, I would like to be able to cycle through the vector of points in order to obtain the closest point. What would be the most efficient way to implement this? I have considered keeping the vector sorted...
40
1801
by: Tameem | last post by:
hi my name is tameem. i am a new c programmer. in a c program i want to give input ""tameem"" and the output will be ""xdphhp"" in a short: the character ""a"" will be replaced by ""d"" i can convert only a character.so how can i convert a word or a sentence my character convert program is given below: #include<stdio.h>
0
9633
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
10305
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
10137
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
8959
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
7483
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
6724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5373
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
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
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

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.