Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there differences between int pointer and char pointer in c?

Tags:

c

pointers

I'm new to C and have a trouble understanding pointers. The part that I'm confused is about char * and int *.

For example, we can directly assign a pointer for char, like

char *c = "c"; and it doesn't make errors.

However, if I assign a pointer for int like I just did, for example int * a = 10;,

it makes errors. I need to make an additional space in memory to assign a pointer for int,

like int *b = malloc(sizeof(int)); *b = 20; free(b);...

Can anyone tell me why?

like image 299
Junyoung Avatar asked Dec 17 '22 12:12

Junyoung


2 Answers

I think you're misunderstanding what a pointer is and what it means. In this case:

int* a = 10;

You're saying "create a pointer (to an int) and aim it at the literal memory location 0x0000000A (10).

That's not the same as this:

int n = 10;
int* a = &n;

Which is "create a pointer (to an int) and aim it at the memory location of n.

If you want to dynamically allocate this:

int* a = malloc(sizeof(int));
*a = 10;

Which translates to "create a pointer (to an int) and aim it at the block of memory just allocated, then assign to that location the value 10.

Normally you'd never allocate a single int, you'd allocate a bunch of them for an array, in which case you'd refer to it as a[0] through a[n-1] for an array of size n. In C *(x + y) is generally the same as x[y] or in other words *(x + 0) is either just *x or x[0].

like image 74
tadman Avatar answered Dec 29 '22 00:12

tadman


In your example, you do not send c to the char 'c'. You used "c" which is a string-literal. For string-literals it works as explained in https://stackoverflow.com/a/12795948/5280183.

like image 45
andrbrue Avatar answered Dec 28 '22 22:12

andrbrue