Simple question is: why do you write
char *foo;
and not
char* foo;
Let me explain: for me (coming from Java) a declaration is something like
<variable-type> <variable-name>;
In the above case I declare a variable named foo
of type char*
(as it is a pointer pointing to char). But wherever I read c/c++/c#-Code it looks like a variable named *foo
of type char
. The compiler does not care about whitespaces but I as a developer do.
tl;dr What I ask for is a good explanation for writing char *foo
instead of char* foo
(what, as explained, seems more convenient for me).
What is the difference between char and char*? char[] is a character array whereas char* is a pointer reference. char[] is a specific section of memory in which we can do things like indexing, whereas char* is the pointer that points to the memory location.
char* is how you declare a pointer to a char variable. It's useful when you want a string with unknown length. 1st example: char name[10];
The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.
char *A[] is an array, and char **A is a pointer. In C, array and pointer are often interchangeable, but there are some differences: 1. with "char *A[]", you can't assign any value to A, but A[x] only; with "char **A", you can assign value to A, and A[x] as well.
Think of the following declaration:
char *p, c;
This declares a pointer to char called p
and a character variable called c
. This shows that it isn't exactly correct to think of variable declaration as having the simple and clear format you described.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With