Doubt about char in C

Asked

Viewed 155 times

2

What does that char* mean and those empty quotes""?:

char *directionX = "";
char *directionY = "";

If you can help me I appreciate.

2 answers

3


char * is a kind of data, we can read it as pointer to char, then means that the variable directionX will have the value of a pointer, ie a memory address that will serve as a pointer to some data, and in case this data must be a character, or at least will be interpreted this way when accessing it by this variable.

It doesn’t mean it has to be just one character, it can be several. A pointer can receive arithmetic and continue at subsequent addresses and function as a array (a vector). When we have a array of characters we call string, or character string.

The way to express a string in code C is by its literal. As a text in a newspaper or other material with content, when the text is a quote you put in quotes, then the literal of string is in quotes. If the quotes are empty you have an empty string.

In this case you are placing an empty text in the static area of your code and this text will end with a null (that terminator is what helps determine when the string ended and pointer should not advance further), and the address where it is will be stored in directionX (the same goes for the other variable). At the moment of accessing you can take the address or you can take the pointer and go straight to the data, that is to say in the static area where the text is, which in this case only has the terminator and nothing else, so it is not very useful.

This code is not very useful because you cannot change the static area value, but you can point the variable to another place where you have more significant text. You could do it later:

directionX = "algo util aqui";

or

directionX = directionX;

I put in the Github for future reference.

even if in this example I do. But in this case the two variables would point to the same object, which is different from two variables pointing to different objects that happen to have the same value.

Beware of indiscriminate use of pointer, it is very easy to corrupt the memory. Experienced programmers live doing this even understanding all the implications of what they do, imagine without understanding everything.

See more about string in C in:

Mainly follow the links within these questions, has quite relevant information. And I advise taking a book, learning randomly does not usually work very well.

Too complicated? Maybe because you’re skipping a few steps. Go step by step.

0

char directionX

Allows only one character, for example 'c', 'a'...etc

char *directionX

It is basically a char pointer that has no static memory.

 char directionX[20]

It is the same as the previous example, but only allows 20 characters in the string

By putting "" we are putting 0 at the beginning, that is, an empty string

Browser other questions tagged

You are not signed in. Login or sign up in order to post.