0

I am new to C and specifically: pointers.

I have the following C-code:

#include <string.h>
#include <stdio.h>

void changeFileName( char *fileName )
{
   char new_name[] = "new_name";
   char temp[] = "";

   printf("... function: changeFileName, BEFORE:   fileName = <%s>\n", fileName);
   fileName = strcpy(temp, new_name);
   printf("... function: changeFileName, AFTER :   fileName = <%s>\n", fileName);

}

int main ()
{
   char *sourceFileName = "sample";

   printf("\nfunction: main, BEFORE:   fileName = <%s>\n\n", sourceFileName);
   changeFileName( sourceFileName );
   printf("\nfunction: main, AFTER :   fileName = <%s>\n\n", sourceFileName);
   return;
}

and upon running I got the following output:

function: main, BEFORE:   fileName = <sample>

... function: changeFileName, BEFORE:   fileName = <sample>
... function: changeFileName, AFTER :   fileName = <new_name>

function: main, AFTER :   fileName = <sample>

I can't figure out why the value of sourceFileName are not changing from the initial value sample to what I'm expecting: new_name.

Bauerhof
  • 155
  • 11
  • `fileName = strcpy(temp, new_name);` does not modify the value `fileName` points to. It modifies the local variable – UnholySheep May 17 '18 at 12:13
  • Besides the dup regarding function arguments, you also have another problem: `fileName = strcpy(temp, new_name);` This is undefined behaviour as the destination buffer can only hold 1 byte (`char temp[] = "";`) – Gerhardh May 17 '18 at 13:21

2 Answers2

0

change void changeFileName( char *fileName ) into void changeFileName( char **fileName )

More info: https://www.tutorialspoint.com/cprogramming/c_function_call_by_reference.htm

Mladen B.
  • 2,784
  • 2
  • 23
  • 34
0

For this fileName = to work you need char **fileName.So you can modify the outside pointer.But even if you use a double pointer it will still point to a local to the function variable.

Also you should declare sourceFileName as const.Becouse modifying a string literal is UB.

Martin Chekurov
  • 733
  • 4
  • 15