Nikunj Banka
Nikunj Banka

Reputation: 11365

Putting an int in an int pointer gives runtime error in C .

The following code works fine in ideone but it gives a runtime error in codeblocks IDE . Is my IDE broken or is there any programming language specific issues .

#include<stdio.h>

int main(){
    int *pointer;
    int num = 45;
    *pointer = num;
    printf("pointer points to value %d", *pointer);
    return 0;
}

Upvotes: 0

Views: 161

Answers (4)

Yingli Yan
Yingli Yan

Reputation: 69

First,you have defined a pointer by "int *pointer".

Then, you try to use "*pointer = num" to realize indirect access —— assign num's value to the memory space which the pointer "pointer" has pointed to.

OK, here is the problem! From your codes, you only have defined a pointer, but you have not made it pointed to a memory space. Making indirect access without doing it is very dangerous. So, you see the runtime error.

Now, you should add "int value;pointer = &value;" to your codes. It will make the pointer "pointer" point to "value". And you can assign "num" to "value" through indirect access "*pointer = num".

In my opinion, you should distinguish definition and indirect access when you study pointer.

I'm a person with poor English. This is my first answer in stack overflow. I hope that my answer can help you. Thank you.

Upvotes: 1

MOHAMED
MOHAMED

Reputation: 43518

replace this

*pointer = num;

by

pointer = &num;

Your pointer should be pointed to a memory space before assignment of value to it.

When you define pointer in this way:

int *pointer;

This meas that you have defined pointer but the pointer is not yet pointing to a memory space. And if you use the pointer directly without pointing it to a memory space (like you did in your code) then you will get undefined behaviour.

pointing the pointer to amemory space could be done by one of the following way:

1) pointing to a static memory

int num;
int *pointer = &num;

num is an int defined as a static. So the pointer could be pointed to the num memory

2) pointing to a dynamic memory

int *pointer = malloc(sizeof(int));

the pointer could be pointed to a dynamic memory. the dynamic memory could be allocated with malloc() and when the memory became useless we can free memory with free(pointer)

Upvotes: 8

Adil
Adil

Reputation: 148110

Assign address of num to pointer as pointer is supposed to hold address not value. You can read more about pointers here

pointer = &num;

Change value of variable through pointer

*pointer = 11;

Upvotes: 1

akp
akp

Reputation: 1823

First of all u should initialize the pointer as to which its trying to point then use it to modify the pointed value..as...

pointer=&num;

now use the pointer to change or access the value to which its pointing.

Upvotes: -1

Related Questions