Jump to content

[ask]pointer to struct

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
kiddies

kiddies

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts
#include<stdio.h>

struct student {

	char firstname[20];

	char lastname[20];

	char SSN[10];

	float gpa;

}student;


main () {

	struct student student_a;


	strcpy(student_a.firstname,"deo");

	strcpy(student_a.lastname,"dum");

	strcpy(student_a.SSN,"23333234");

	student_a.gpa=2009.20;


	printf( "firstname: %s\n",student_a.firstname);

	printf( "lastname: %s\n",student_a.lastname);

	printf( "SSN: %s\n",student_a.SSN);

	printf( "GPA: %s\n",student_a.gpa);

}

this code can be executed

but how if we use method "Pointers to Structs", what a piece of source i change...help me...

i was try to change a code like this
#include<stdio.h>

struct student {

	char firstname[20];

	char lastname[20];

	char SSN[10];

	float gpa;

}student;


main () {

	struct student *student_a;


	strcpy(student_a->firstname,"deo");

	strcpy(student_a->lastname,"dum");

	strcpy(student_a->SSN,"23333234");

	student_a->gpa=2009.20;


	printf( "firstname: %s\n",student_a->firstname);

	printf( "lastname: %s\n",student_a->lastname);

	printf( "SSN: %s\n",student_a->SSN);

	printf( "GPA: %s\n",student_a->gpa);

}

help to fix my code...

#2
theonejb

theonejb

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
Try this:
#include<stdio.h>
#include <string.h>
#include <stdlib.h>

struct student {
	char firstname[20];
	char lastname[20];
	char SSN[10];
	float gpa;
}student;

main () {
  struct student *student_a = malloc(sizeof(struct student));
  
  strcpy(student_a->firstname,"deo");
  strcpy(student_a->lastname,"dum");
  strcpy(student_a->SSN,"23333234");
  student_a->gpa=2009.20;
  
  printf( "firstname: %s\n",student_a->firstname);
  printf( "lastname: %s\n",student_a->lastname);
  printf( "SSN: %s\n",student_a->SSN);
  printf( "GPA: %f\n",student_a->gpa);


#3
runchman

runchman

    Newbie

  • Members
  • PipPip
  • 20 posts
To kind of explain the malloc():

Essentially Kiddies when you create that pointer variable, it "points" to an area in memory where the data is going to be stored.

All you've declared at that point is that you have a variable that points to someplace - the malloc() above is what actually says "Give me an area of memory big enough to hold this structure".

Without this malloc(), when you assign data to your pointer, you'd be writing over something important in memory.

- John

#4
kiddies

kiddies

    Programmer

  • Members
  • PipPipPipPip
  • 130 posts
oooowwww, if wanna use spointer to strcut w have to give alocation caribale memory like this

struct student *student_a = malloc(sizeof(struct student));

for make
student_a->firstname,"deo"

i try that code run n there is no segment fault there