Vaguely when should i malloc

I know that if I enter a string into a pointer variable, I would do malloc based on the size of the input received.

But what if I use a pointer variable to use in strchr? For example, if I want the pointer to point to the character "z" in a string.

char *pointer;

pointer=strchr(string,'z');

Do I need a malloc pointer? Or is it not necessary?

+4
source share
4 answers

You do not need to allocate any memory here. The Strchr function returns a pointer to the first occurrence of char in the string, if it exists. If the given string does not contain char, then null is returned.

, - , . , .

0

strchr C.

, C, malloc

0

malloc() , . , . , , , , . , .

0

You should use malloc if you need a system to provide you with memory to store data. For example, if you want to save a string, you must allocate memory for it

char* s = malloc(10);
strcpy(s, "something");

If you only need a pointer that indicates what is already in memory, you should not select it, in your case, the function strchrreturns a pointer that points to the position in memory where the char is cin the strings

char* c;
c = strchr(s, 'm');
0
source

Source: https://habr.com/ru/post/1625122/


All Articles