2

The argv array is a list pointers, each pointing to the respective argument, with the first element the number of command line arguments, correct?

My question is how do I pass a string argument to a function? In this small example I'm just trying to print the text I write as argument in the command line.

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

void ptest(char *);

int main(int argc, char const *argv[])
{
    ptest(argv[1]);
    return 0;
}

void ptest(char *ptr)
{
    printf("%s\n", ptr);
}

This code does not compile. It gives the following compilation errors:

teste2.c:8:8: warning: passing 'const char *' to parameter of type 'char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
        ptest(argv[1]);
              ^~~~~~~
teste2.c:4:18: note: passing argument to parameter here
void ptest(char *);
             ^
S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Miguel
  • 2,738
  • 3
  • 35
  • 51

1 Answers1

6

That's not you issue. Your issue is that you've added the const keyword, meaning that you have a pointer to an array of values, where the array of values can't be changed.

You can check out this for a better explanation.

In your code:

int main(int argc, char const *argv[])

remove the const and your code will compile:

int main(int argc, char *argv[])
Community
  • 1
  • 1
Archmede
  • 1,592
  • 2
  • 20
  • 37
  • 2
    Removing the `const` is fine but consider changing `ptest` to accept a `const char *` instead. – agbinfo May 09 '17 at 22:51