Doubt regarding pointer

5

I have a question regarding C. Because when I declare as argument in function main: char* argv[] instead of char argv[] I can access the information. I know one is a pointer. Because I can not access when it is not a pointer.

#include <stdio.h>

int main (int argc, char* argv[])
{
    printf("%s", argv[1]);
}
    
asked by anonymous 11.04.2017 / 17:31

3 answers

4

You are accessing an array of strings . The [] represents the array and the char * represents the string . This is necessary because the command line can pass several arguments, and all are strings .

In C there is no string with its own concept, it is usually represented by an array or pointer, the most common character.

So there are two distinct things, so it needs to be used this way.

In C it's rare, but there are those who make typedef string char *; to use string instead of char * .

If it were

int main(int argc, string argv[])

Would you understand? It's the same thing.

Can not access without the pointer because there is only an array of characters and not an array of strings , which is expected. In fact you even have access, but it will not be what you expect. You have to use the right type for what you need.

    
11.04.2017 / 17:54
2

Because C strings are character vectors, when you declare char * argv [], you are declaring a vector of strings.
To access index 1 through n-times, 0 and the name passed in the command line.

This is an example:

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

int main()
{
    char *nomes[] = {"joao", "maria", "pedro"};

    for(int i=0; i<sizeof(nomes) / sizeof(char* ); i++) {
        printf("%s\n", nomes[i]);
    }
    return 0;
}

link

    
11.04.2017 / 17:59
1

Just to better understand, pointers are useful when a variable has to be accessed in different parts of a program. Your code can have multiple pointers pointing to the variable that contains the desired data.

Situations where pointers are useful:

  • Dynamic memory allocation
  • Array manipulation
  • To return more than one value in a function
  • List, stack, tree, and graph reference
11.04.2017 / 18:03