0

I'm newbie in C language, so probably this is a stupid qeustions, but i don't know what to do. this is my trouble:

why this code doesn't print nothing?

#include <stdio.h>
#include <stdlib.h>


void function(char* valor);

main()
{
char* valor;
int s;

    valor=(char*)malloc(101*sizeof(char));
    function(valor);
    printf("%s\n",valor);

return 0;
}

void function(char* valor)
{

    valor="ciao";

}    

and this print the string i want? ("ciao")

#include <stdio.h>
#include <stdlib.h>

main()
{
char* valor;

    valor=(char*)malloc(101*sizeof(char));
    valor="ciao";
    printf("%s\n",valor);

return 0;
}
  • 2
    http://c-faq.com/ptrs/passptrinit.html – cnicutar May 11 '15 at 15:53
  • 1
    FYI: You are allocating memory and assigning a pointer to it. Then you are re-assigning the pointer to a static string which is abandoning the memory you allocated. Memory Leak! – Steve Wellens May 11 '15 at 15:57

2 Answers2

1

The variable valor inside the function and the variable valor in main are different variables.

When you change the value of valor inside the function, nothing happens to valor in main.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

Your function() sets its internal copy of the 'valor' pointer to point to a string constant. The original copy in the stack of main() remains intact, i.e. garbage (or possibly zero).