0

I am trying to find what is the issue with below program.

#include <stdio.h>

void func(char *name, char *buff)
{
   name = &buff[0];
}


void main()
{
   char name[4] = {'A','B','C','D'};
   char buff[4] = {'E','F','G','H'};
   printf("%s \n",name);
   func(&name[0], &buff[0]);
   printf("%s \n",name);
}

Output:: ABCD ABCD

Why isnt pointer getting reassigned in the method func() ?

bolov
  • 72,283
  • 15
  • 145
  • 224
Ravi
  • 3
  • 2
  • Note that `name` is not a string as it does not have space for a null terminator, so printing it with `%s` is invoking undefined behavior. – Chris Apr 15 '23 at 04:41

1 Answers1

1

The parameters to func() are passed by copy, so the name = &buff[0]; isn't changing the name variable within the program scope of the main method. It is just like wondering why

#include <stdio.h>

void func(char name, char buff)
{
   name = buff;
}


void main()
{
   char name = 'a';
   char buff = 'b';
   printf("%s \n",name);
   func(name, buff);
   printf("%s \n",name);
}

Outputs

a
a