Access to pointer on main

Asked

Viewed 137 times

6

Why in the statement as argument in function main(): char* argv[] instead of char argv[] i can access the information. I know one is pointer. I can’t access when it’s not pointer.

#include <stdio.h>

int main (int argc, char* argv[])
{
    printf("%s", argv[1]);
}

3 answers

5


You are accessing a 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 a array or the most common character pointer.

So it’s two different things, so it needs to be used this way.

In C it’s rare, but some do typedef string char *; to use string in place of char *.

If it were

int main(int argc, string argv[])

I put in the Github for future reference.

would you understand? It’s the same thing.

Can’t access without the pointer array of characters and not a array of strings, which is what is expected. Actually you can access, but it won’t be what you expect. You have to use the right type for what you need.

3

Because in C strings are character vectors, when you declare char* argv[], you are declaring a string array.
To access from index 1 to n-times, 0 and the name passed on 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;
}

https://ideone.com/6NOCI2

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 allocation of memory
  • Arrays manipulation
  • To return more than one value in a function
  • Reference for lists, stacks, trees and graphs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.