how to relate pointers to char with Strings

1

Good afternoon I need some help to get closer to my solution, in C when it is executed by console and files are included these are declared in the main statement with a pointer to char pointers (array of Strings) but then I need to store those values in char [] or char * type variables by a function to achieve modularity and I can not. I attach part of my code

int main (int argc, char **argv)
{
char *archivo1,*archivo2;
argc=3;
nombreArchivos(cant,argv,archivo1,archivo2);// no pongo ampersand al ser cadenas 
}

void nombreArchivos(int cant, char **argv, char *a1, char* a2)
{
*a1 = argv[1];
*a2 = argv[2];
}

but when I return to the main I lose the values. thank you very much

    
asked by Franco Rolando 05.05.2018 в 16:44
source

1 answer

2

If you want a function to change the values of something it has received as a parameter, you should always pass a pointer to that parameter.

In your case, you pretend that archivo1 and archivo2 are modified, so the call to the function must pass the address of those variables, that is, &archivo1 , &archivo2 . It matters little whether these variables are pointers or not, if you want to change the value (in the case of the pointer you want to change where they point), you have to pass your address.

This forces you to change the declaration of those parameters, since a1 and a2 are no longer pointers to character, but pointers to pointers (since they will receive the address of a pointer).

The following is an example that works (I do not understand, by the way, the role of the parameter cant , nor why you change the value to argc , so I corrected that part).

#include <stdio.h>

void nombreArchivos(int cant, char **argv, char **a1, char **a2)
{
    *a1 = argv[1];
    *a2 = argv[2];
}

int main (int argc, char **argv)
{
    char *archivo1,*archivo2;
    int cant=3;   // ??
    nombreArchivos(cant,argv,&archivo1,&archivo2);
    printf("archivo1=%s\n", archivo1);
    printf("archivo2=%s\n", archivo2);
    return 0;
}
    
answered by 05.05.2018 / 20:05
source