473,789 Members | 2,806 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 1319
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
1255
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
2594
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
10710
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
1802
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
9511
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
10412
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
10200
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...
1
10142
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
9021
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
7529
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
6769
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
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2909
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.