2

I am new to C, and I am facing this problem when practicing.
The struct:

 typedef struct {
        char name[20];
        int score[3];
        int no;
    } Student;

The initialize:

Student *pStudent;
strcpy(pStudent->name,"Kven");
pStudent->score[0]=1;
pStudent->score[1]=2;
pStudent->score[2]=3;
pStudent->no=1;

If the "pStudent" is not a pointer I can get it right. But if it is a pointer, I will always get a "bad access" error. How to solve it if I must use a pointer? Thank you.

5
  • 1
    Without initialization the pointer will not actually point anywhere. You need to initialize the pointer to make it point somewhere valid, either to another structure or by dynamically allocating memory for the strcture Commented Apr 15, 2015 at 13:42
  • You have to make the pointer point at allocated memory. Pointers are things that point at other memory locations, they aren't a "special sort of handle" or anything like that. Commented Apr 15, 2015 at 13:42
  • 1
    Why the downvote? The question might be obvious to some but it's well-posed with a good example. Commented Apr 15, 2015 at 13:43
  • @Bathsheba doesn't show any research effort ; any introductory C book will cover this Commented Apr 15, 2015 at 13:43
  • It remains perfectly unclear 1) why you must use a pointer (I'm guessing artificial teacher requirement) and 2) why you would want to use dynamic memory allocation in this case. Lots of people told you to do so but none explained why it would make sense to do so. Commented Apr 15, 2015 at 14:00

5 Answers 5

6

A variable of type pointer stores the address in memory of another variable (it points to another variable).

Your variable pStudent is not initialized. It doesn't point to anything. In fact, it contains some garbage value that, most of the times, is the address of a memory area where the program is not allowed to write. This is why when you attempt to write there (the call to strcpy()) the operating system slaps your program over its "hand" and terminates it with the error message you mentioned.

How to correctly use pointers

One usage of pointers is to point to a certain variable that is statically allocated (defined in the program):

Student s, *pStudent = &s;

This example declares the variable s of type Student and the variable pStudent that points to it. Notice it is initialized with &s which is the address of s. Now, your code uses pStudent to initialize the fields of s.

Another usage of pointers is to dynamically allocate memory during runtime:

Student *pStudent;
pStudent = malloc(sizeof(Student));

In this situation, pStudent is initialized with the address of a new variable of type Student that is created during runtime (it doesn't have a name) by calling malloc(). malloc() allocates a block of memory (of the specified size) and return its address.

When you don't need it, you have to free the memory allocated by malloc() (using free()) for reuse:

free(pStudent);

After this call, the value of the variable pStudent doesn't change, it still points to the same address but it is invalid and using it produces undefined behaviour. You have to put the address of another Student structure in pStudent (using one of the two ways presented here) before using it again.

Sign up to request clarification or add additional context in comments.

Comments

3
Student *pStudent;

should be

Student *pStudent = malloc(sizeof(Student));

Allocate memory for the pointer before writing data once done using it

free(pStudent);

5 Comments

but then you have to free at the and
Someone who has enough basic C sense to free dynamic pointers wouldn't ask the question above.
Any particularly reason why you would use dynamic allocation in this case?
@Lundin Just by the first look it looks like OP wants to try out dynamic memory allocation for the structure. Since i see a pointer declared but not initialized I went ahead and suggested allocating memory for the pointer so that the rest of the code stays instact
@Gopi Fair enough, even though pointer != dynamic allocation.
3

You don't allocate any memory, you just allocate a pointer. You'll need to study pointers and how they work.

Fix the code like this:

Student student;
strcpy(student.name,"Kven");
student.score[0]=1;
student.score[1]=2;
student.score[2]=3;
student.no=1;

Alternatively you could allocate memory dynamically. But it doesn't make any sense in this case (and yet I bet at least 3 people will post answers telling you to do that...). Plus you really need to study pointers before doing dynamic allocation.

Student *pStudent = calloc(1, sizeof(Student);

if(pStudent == NULL)
{
  // error handling
}

strcpy(pStudent->name,"Kven");
pStudent->score[0]=1;
pStudent->score[1]=2;
pStudent->score[2]=3;
pStudent->no=1;

...

free(pStudent);

6 Comments

If the "pStudent" is not a pointer I can get it right. But if it is a pointer, I will always get a "bad access" <-- I think OP was asking specifically about dynamic allocations
Ironically, while I wrote this, exactly 3 people posted answers recommending malloc, with no rationale whatsoever why...
@tux3 There is nothing in their post hinting about that, nor does it make any sense to use it in this case.
@Lunding the very last sentence of the question is "How to solve it if I must use a pointer?". Otherwise I'd completely agree.
@tux3 You aren't forced to use pointers. C allows you to allocate variables as you please. Now if the OP has some homework assignment with completely artificial requirements, that's too bad for them. I'd rather post answers that applies to C programming in the real world. If you must use a pointer, then simply take my first example, then add Student* pStudent = &student;. Success!
|
2
Student *pStudent;

creates a pointer of type Student*. This pointer is not initialized and points to some "random" location. Allocate memory for it using malloc(or calloc) from stdlib.h:

pStudent = malloc(sizeof(Student));

and then free it after its use using:

free(pStudent);

4 Comments

Any particularly reason why you would use dynamic allocation in this case?
@Lundin , "How to solve it if I must use a pointer?" is mentioned in OP's post. OP has already mentioned that he/she knows how to do it without a pointer.
Pointer != dynamic allocation.
@Lundin , Fair enough. I'll take care to post both the ways to achieve this next time onwards.
1

You need to allocate memory for your structure first.

You can allocate memory with:

Student *pStudent = malloc(sizeof(Student));

And then you must release it at the end with

free(pStudent);

6 Comments

Any particularly reason why you would use dynamic allocation in this case?
I wouldn't. But OP asked specifically about dynamic allocation.
Pointer != dynamic allocation.
@Lundin I'm having trouble believing that you're arguing in good faith. Let's agree to disagree and leave it at that.
OP did not ask about dynamic allocation
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.