Character strings as pointers in c

5

I am learning C and I understand perfectly the pointers and their relation with the arrays, but my problem comes with the character strings. We declare a string of characters like this:

char cadena[] = "Hola";

is equivalent to:

char cadena[] = {'H','o','l','a','
char *getCadena (){
    static char cadena[] = "Hola"; //static para que su dirección en la memoria sea global
    return cadena;
}
'}

and therefore if you want a function to return a string of characters you have to make it static so that the memory address is valid outside the scope of the function:

char *cadena = "Hola";

What I do not understand is that the compiler does when you declare the string of characters like this:

char *getCadena (){
char *cadena= "Hola";
return cadena;
}

declare the array static? I ask it because in testing it I have seen that even declaring a string of characters in that way within a function can be returned without problems, so the address has to be global in some way:

char cadena[] = "Hola";

Thanks in advance and greetings

    
asked by raul 25.08.2016 в 20:43
source

1 answer

5

Allocaminento estatico

  

What I do not understand is that the compiler does when you declare the string of characters like this:

     

char *cadena = "Hola";

The compiler creates the literal "Hello" in a memory-only zone and cadena points to that address, that is: it is the pointer cadena what is in the stack, not the literal "Hello " When you return, you return the literal address (where cadena pointed) and therefore it is safe to return.

The use of static creates a difference, because the variable that would normally remain in the stack is actually in the static memory. This has another use case, it is for when a function needs to store a state between different calls.

Allocaminento automatico

now when you do ...

char cadena[] = "Hola";

creates the literal "Hello" in a read-only memory area, but when the function is invoked, it copies the literal to the string array that is allocated in the stack.

Here is another difference, the latter can be modified as long as its maximum length is not changed. Well, it's a copy.

It is not safe to override the address of this array because the entire chain is in the stack.

Allocaminento dynamic

There is another way to allocate memory in c, it is using malloc and free that are used respectively to reserve memory and release a previous reservation.

This type of allocamiento is done in the Heap, I mean dynamic memory.

This type of allocations are safe to return from a function, but you should not forget to release it (with free ) otherwise the program will end up using all the memory and will stop by OUT_OF_MEMORY

    
answered by 26.08.2016 в 02:51