Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char *foo vs char* foo [closed]

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).

like image 416
Dominik Schreiber Avatar asked Mar 04 '12 20:03

Dominik Schreiber


People also ask

What is the difference between char * and char *?

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.

What does the * after char mean?

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];

Should I use char * or char []?

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.

What is * a [] in C?

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.


1 Answers

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.

like image 106
Adam Zalcman Avatar answered Sep 28 '22 00:09

Adam Zalcman