473,566 Members | 2,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

pointer to struct

can´t understand why the program above not works.
thanks all
#include <stdio.h>
#include <stdlib.h>

#define SIZE 3

struct peoples
{
int code;
char name[20];
float value;
};

int main()
{
int a;
struct peoples *people;
people=(struct peoples *)malloc(SIZE*s izeof(struct peoples));
for(a=0;a<SIZE; a++)
{
people->code=a;
scanf("%s",peop le->name);
scanf("%f",peop le->value);
people++;
}
for(a=0;a<SIZE; a++)
{
printf("%d",peo ple->code);
printf("%s",peo ple->name);
printf("%f",peo ple->value);
people++;
}
}

Dec 6 '06 #1
14 2527
ls
You only have on struct and one pointer. Why are you incrementing the
pointer? Why are you looping? Maybe you need an array of structs 3
(SIZE) pointers and need to loop through the array to allocate structs,
loop to assign values, then loop to acces the values.

On Dec 6, 9:48 am, "povoação" <okle...@gmail. comwrote:
can´t understand why the program above not works.
thanks all

#include <stdio.h>
#include <stdlib.h>

#define SIZE 3

struct peoples
{
int code;
char name[20];
float value;

};int main()
{
int a;
struct peoples *people;
people=(struct peoples *)malloc(SIZE*s izeof(struct peoples));
for(a=0;a<SIZE; a++)
{
people->code=a;
scanf("%s",peop le->name);
scanf("%f",peop le->value);
people++;
}
for(a=0;a<SIZE; a++)
{
printf("%d",peo ple->code);
printf("%s",peo ple->name);
printf("%f",peo ple->value);
people++;
}

}
Dec 6 '06 #2
"povoação" <ok*****@gmail. comwrites:
int main()
I'd recommend using the prototype form:
int main(void)
{
int a;
struct peoples *people;
This is very creative naming, to give the pointer to the
beginning of an array a relatively singular name, and the
structure type that the array contains a relatively plural name.
Most programmers would probably do it differently, e.g.
struct person *people;
people=(struct peoples *)malloc(SIZE*s izeof(struct peoples));
I don't recommend casting the return value of malloc():

* The cast is not required in ANSI C.

* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.

* If you cast to the wrong type by accident, odd failures can
result.

In unusual circumstances it may make sense to cast the return value of
malloc(). P. J. Plauger, for example, has good reasons to want his
code to compile as both C and C++, and C++ requires the cast, as he
explained in article <9s************ *****@nwrddc01. gnilink.net>.
However, Plauger's case is rare indeed. Most programmers should write
their code as either C or C++, not in the intersection of the two.

When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:

int *x = malloc (128 * sizeof (int)); /* Don't do this! */

Instead, write it this way:

int *x = malloc (128 * sizeof *x);

There's a few reasons to do it this way:

* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.

This is more of a problem in a large program, but it's still
convenient in a small one.

* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
for(a=0;a<SIZE; a++)
{
people->code=a;
scanf("%s",peop le->name);
You need to specify a maximum length, or this can lead to a
buffer overflow.
scanf("%f",peop le->value);
You forgot to take the address: &people->value.
people++;
}
for(a=0;a<SIZE; a++)
{
printf("%d",peo ple->code);
printf("%s",peo ple->name);
printf("%f",peo ple->value);
people++;
}
This isn't going to work, because in your first loop you already
advanced "people" past the records you're trying to print. I'd
suggest dropping the "people++" from both loops and using array
index notation instead for each member reference,
e.g. people[a].code.
}

--
"In My Egotistical Opinion, most people's C programs should be indented six
feet downward and covered with dirt." -- Blair P. Houghton
Dec 6 '06 #3
povoação wrote:
can´t understand why the program above not works.
For many reasons.
people=(struct peoples *)malloc(SIZE*s izeof(struct peoples));
for(a=0;a<SIZE; a++)
{
people->code=a;
scanf("%s",peop le->name);
scanf("%f",peop le->value);
people++;
}
You're incrementing people (pointer to struct peoples), which after the
first for loop points to where? You'd be better of with:
people[a].code = a;
Secondly, scanf() arguments should be pointers so use:
scanf ("%f", &people[a].value);
For char arrays, you can use either people[a].name or
&people[a].name[0]. Some prefer the second version.
Thirdly, you're not checking for scanf() return values. If someone
doesn't enter a float when you expect it, your program will misbehave.
Also, your people[a].name is limited to 20 characters, it won't work if
someone enters more than that - check the scanf() man page.
}
for(a=0;a<SIZE; a++)
{
printf("%d",peo ple->code);
printf("%s",peo ple->name);
printf("%f",peo ple->value);
people++;
}
Again, don't increment people, use people[a]. Outputting a newline now
and then may also be a good thing.

Dec 6 '06 #4
"ls@qustation.c om" <ls******@gmail .comwrites:
You only have on struct and one pointer.
Read his code again. He allocates an array of SIZE structs.
--
"IMO, Perl is an excellent language to break your teeth on"
--Micah Cowan
Dec 6 '06 #5
I modified to people[a] instead pointer and works well, but I´m
learning pointers and I can´t understand cause was not working with
pointer.
I corrected scanf, I´d miss &.
I try modify also the line people=malloc(S IZE * sizeof *people); and
i got error at compile time invalid conversion from void* to peoples*.

thanks

On Dec 6, 4:10 pm, "matevzb" <mate...@gmail. comwrote:
povoação wrote:
can´t understand why the program above not works.For many reasons.
people=(struct peoples *)malloc(SIZE*s izeof(struct peoples));
for(a=0;a<SIZE; a++)
{
people->code=a;
scanf("%s",peop le->name);
scanf("%f",peop le->value);
people++;
}You're incrementing people (pointer to struct peoples), which afterthe
first for loop points to where? You'd be better of with:
people[a].code = a;
Secondly, scanf() arguments should be pointers so use:
scanf ("%f", &people[a].value);
For char arrays, you can use either people[a].name or
&people[a].name[0]. Some prefer the second version.
Thirdly, you're not checking for scanf() return values. If someone
doesn't enter a float when you expect it, your program will misbehave.
Also, your people[a].name is limited to 20 characters, it won't work if
someone enters more than that - check the scanf() man page.
}
for(a=0;a<SIZE; a++)
{
printf("%d",peo ple->code);
printf("%s",peo ple->name);
printf("%f",peo ple->value);
people++;
}Again, don't increment people, use people[a]. Outputting a newline now
and then may also be a good thing.
Dec 6 '06 #6
"povoação" <ok*****@gmail. comwrites:
I try modify also the line people=malloc(S IZE * sizeof *people); and
i got error at compile time invalid conversion from void* to peoples*.
It sounds like you're using a C++ compiler.
--
Ben Pfaff
email: bl*@cs.stanford .edu
web: http://benpfaff.org
Dec 6 '06 #7
povoação wrote:
I modified to people[a] instead pointer and works well, but I´m
learning pointers and I can´t understand cause was not working with
pointer.
Well, think of it this way. You are allocating memory that will hold
three structures. malloc() returns the pointer to this memory and you
assign it to variable people. When you increment people (people++),
people will then point to the next element and you no longer have a
pointer to the allocated block:
| 0 | 1 | 2 | | 0 | 1 | 2 |
^ ^
people people

But in order to print out the values in the second loop, you do need
the original pointer, however people is not pointing there anymore.
Either access the allocated memory as an array (people[a]), or remember
the original pointer and after before the second loop, set the people
to point there.
I try modify also the line people=malloc(S IZE * sizeof *people); and
i got error at compile time invalid conversion from void* to peoples*.

thanks
I cannot comment on the sizeof usage, as my perception differs a lot
from what Ben said. I never use sizeof without ()s and I never use it
on variables, but types insetad. The reason for that is the following:
char buf[10];
...
some_function (sizeof (buf));
If in future the buf type is changed from an array to a char *,
sizeof(buf) will get a _very_ different meaning. In small projects, the
bug will be easy to find, however once you have 100,000 lines of code
and the crash only happens on a customer's machine to which you don't
have access (and, of course, the bug is not reproducible in the lab),
you could spend days before the problem is found. Been there, done
that. So, where Ben said "Don't do this!", I always do =)
--
WYCIWYG - what you C is what you get

Dec 6 '06 #8
It´s true. I saved .c and now compiles. I´m using Dev-C++ now.
Can help me to fix the program to work with pointers notation?

On Dec 6, 5:05 pm, Ben Pfaff <b...@cs.stanfo rd.eduwrote:
"povoação" <okle...@gmail. comwrites:
I try modify also the line people=malloc(S IZE * sizeof *people); and
i got error at compile time invalid conversion from void* to peoples*.It sounds like you're using a C++ compiler.
--
Ben Pfaff
email: b...@cs.stanfor d.edu
web:http://benpfaff.org
Dec 6 '06 #9
"povoação" <ok*****@gmail. comwrites:
Can help me to fix the program to work with pointers notation?
If a problem is easily solved using array notation, then there is
no need to solve it another way.
--
A competent C programmer knows how to write C programs correctly,
a C expert knows enough to argue with Dan Pop, and a C expert
expert knows not to bother.
Dec 6 '06 #10

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

Similar topics

3
7639
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
10
4093
by: Kieran Simkin | last post by:
Hi, I wonder if anyone can help me, I've been headscratching for a few hours over this. Basically, I've defined a struct called cache_object: struct cache_object { char hostname; char ipaddr; };
5
2522
by: Danilo Kempf | last post by:
Folks, maybe one of you could be of help with this question: I've got a relatively portable application which I'm extending with a plugin interface. While portability (from a C perspective) is going to hell just by using dlopen()/LoadLibrary() respectively, I'm still trying to get it as clean as possible. I have a number of different...
2
3048
by: Immo Birnbaum | last post by:
Hi, I'm trying to solve a programming lab assignment for my college C programming course, but as they taught us two semesters of Java before teaching us any C, I'm having problems with all the aspects of pointers. I'd appreciate if anybody could help me with the following problem: I tried to learn how to use malloc, free, and the * and &...
4
3590
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
10
353
by: junky_fellow | last post by:
K&R say that, It is guaranteed that 1) a pointer to an object may be converted to a pointer to an object whose type requires less or equally strict storage alignment and 2) back again without change. My question is that, is it legal to dereference the intermediate pointer (the pointer with less strict alignment that we get after...
5
4319
by: Johs32 | last post by:
I have a struct "my_struct" and a function that as argument takes a pointer to this struct: struct my_struct{ struct my_struct *new; }; void my_func(struct my_struct *new); I have read that there is no difference between giving this function a
2
1765
by: Chad | last post by:
The following question stems from the following thread on comp.lang.c: http://groups.google.com/group/comp.lang.c/browse_thread/thread/0ad03c96df57381a/5f20260b30952fe7?hl=en#5f20260b30952fe7 I was sort of mystified by a comment made by Eric. And I quote: "You might also be confused by the fact that each `struct my_struct' contains a...
12
3861
by: gcary | last post by:
I am having trouble figuring out how to declare a pointer to an array of structures and initializing the pointer with a value. I've looked at older posts in this group, and tried a solution that looked sensible, but it didn't work right. Here is a simple example of what I'm trying to accomplish: // I have a hardware peripheral that I'm...
2
3258
by: Mike | last post by:
Hi, I am new to C and having problems with the following program. Basically I am trying to read some files, loading data structures into memory for latter searching. I am trying to use structres and arrays of pointers to them. I have gotten the program to compile with gcc on WinXP. If the file i read doesnt have alot of records, it runs...
0
7673
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...
0
7584
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...
0
7893
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. ...
1
7645
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...
0
7953
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...
0
6263
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...
1
5485
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...
0
3643
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...
1
1202
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.