Juannillus Juannillus - 13 days ago 6
C Question

Modifying the value of an array in a function by a pointer in C

I have read quite a few articles about how to do it, but I can't seem to get my head about what is the problem in my code. I have done multiple test, but none seems to work.

My problem is pretty easy, I have declared an array, pass it to a function, modify it in the function, and return the modified value to the main.

I think I know how to do it, by passing the value by reference. I have tested with integer variables and it works, but I can't seem to get to work with arrays of characters.

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>

void func1(char *puntf);

int main ()
{
char DIRECTORIO[200];
char *punt = 0;

getcwd(DIRECTORIO, 200);
punt=&DIRECTORIO;

printf("DIR in MAIN is: \t%s\n\n", DIRECTORIO);
printf("PUNT in MAIN is: \t%s\n\n", punt);

func1(punt);

printf("DIR in MAIN after func1 is: \t%s\n\n", punt);

return 0;
}

void func1(char *puntf)
{
char DIRF[200]="/Users";
char *puntero = 0;

printf("puntf from MAIN in func1 es: \t%s\n\n", puntf);
printf("DIRF in func1 is: \t%s\n\n",DIRF);
puntf=DIRF;

printf ("puntero in func1 is:\t%s\n\n", puntero);
printf ("puntf in func1 is:\t%s\n\n", puntf);

}


If I use *puntf=DIRF; it changes the first letter of the directory from 'C' to 'P'.

If I use *puntf=*DIRF; it changes the first letter of the directory from 'C' to '\'.

In several other options, the executable crashes.

I have tried lots of possibilities while assigning DIRF value to puntf (really lots), but I can't figure out how to get it.

Please, could anyone point me to my mistake?

Thanks,
Juan

Answer

There are many issues. First of all punt = &DIRECTORIO; doesn't compile.

puntf=DIRF; will only change the local puntf, but not the punt pointer in main.

And anyway with puntf=DIRF; you are trying to assign a pointer to the local variable DIRF. Be aware that puntf=DIRF; doesnt copy a string, it only assigns a pointer. If you want to copy a string, you need the strcpy function.

You probbaly want this:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>

void func1(char *puntf);

int main()
{
  char DIRECTORIO[200];
  char *punt = 0;

  getcwd(DIRECTORIO, 200);

  printf("DIR in MAIN after func1 is: \t%s\n\n", DIRECTORIO);
  func1(DIRECTORIO);
  printf("DIR in MAIN after func1 is: \t%s\n\n", DIRECTORIO);

  return 0;
}

void func1(char *puntf)
{
  char DIRF[200] = "/Users";
  printf("puntf from MAIN in func1 es: \t%s\n\n", puntf);
  printf("DIRF in func1 is: \t%s\n\n", DIRF);

  strcpy(puntf, DIRF);

  printf("puntf in func1 is:\t%s\n\n", puntf);
}