Let’s understand what’s making each line:
char nome[12] = "programador";
Created a space in data stack for a pointer to characters that will be allocated in a static area of the application. There are 12 characters (11 useful because of the terminator). This pointer is called nome
.
char *ponteiro = nome;
Created a space in the data stack for a pointer (4 or 8 bytes depending on the architecture) and placed the pointer to the previous space referenced as nome
.
return ponteiro;
Ended the execution of the function by returning (copying) the value of this pointer, "destroying" every area allocated in this function (actually it is only unavailable)
Now back to the main function. ponteiro
here has the same value of`called function pointer, there was a copy.
printf("%s\n", ponteiro); /*Saida = - (*/
The pointer there is pointing and portando accessing the memory area that was destroyed. Anything can happen. This is called undefined behavior.
When you put one static
in the variable is saying that you want to allocate the content in the static area of your application, an area that is never destroyed (and other than the stack), then the die is there as you wish.
This code better demonstrates what you want:
#include <stdio.h>
#include <string.h>
char *local(void) {
static char nomex[12] = "aaaaaaaaaa";
char nome[12] = "programador";
char *ponteiro = nome;
printf("%s\n", nome);
printf("%s\n", ponteiro);
printf("%p\n", (void *)ponteiro);
printf("%p\n", (void *)nome);
printf("%p\n", (void *)nomex);
printf("%p\n", (void *)&ponteiro);
return ponteiro;
}
int main(void) {
char *ponteiro = local();
printf("%s\n", ponteiro);
printf("%c\n", ponteiro[0]);
printf("%p\n", (void *)ponteiro);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Now look at this:
#include <stdio.h>
#include <string.h>
char *local(void) {
static char nomex[12] = "aaaaaaaaaa";
char nome[12] = "programador";
char *ponteiro = nome;
return ponteiro;
}
int main(void) {
char *ponteiro = local();
printf("%s\n", ponteiro);
printf("%c\n", ponteiro[0]);
printf("%p\n", (void *)ponteiro);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Depending on the compiler will give different results, even not changing anything in the variables.
Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site
– Maniero