1

I'm studying C in order to start doing some fun low-level code stuff, and I've stumbled into a scenario which I can't wrap my head around, and I'm sure it's because I don't have a lot of experience with it.

Currently my code is very simple: it takes some arguments, and gets the first parameter passed to main, and stores it as a path string. The first question that came to mind, was whether it would be correct to store the main params as char *args[] or char **args, and I decided to go with char **args since according to this question there could be some scenarios where the first would not be accessible, and I just wanted to make a code that would be as complete as possible, and learn the whys on the process.

Here's is the code:

int main(int argc, char **args) { if (args[1] == NULL) return 1; // Get path of input file char *path = &*args[1]; fputs(path, stdout); return 0; } 

Given the code above, what would be a better way of fetching the value stored in *args[1]? It seems very cryptic when I look at it, and it took me a while to get to it as well.

My understanding is that char **args, is a pointer, to an array of pointers. Thus, if I'm to store a string or any other value for later use in one of the indexes of args, I would have to assign a new pointer to a memory location (*path), and assign the value of the given index to it (&*args[i]). Am I over complicating things? Or is this thought process correct?

2
  • 2
    Doesn't char* path = args[1]; work? Commented Apr 9, 2021 at 21:52
  • Unless argc > 1 this is undefined behaviour. Check before accessing. Commented Apr 9, 2021 at 21:53

2 Answers 2

3

For starters these two function declarations

int main(int argc, char **args) 

and

int main(int argc, char *args[]) 

are fully equivalent because the compiler adjusts the parameter that has an array type to pointer to the array element type.

In the initializer expression of this declaration

char *path = &*args[1]; 

applying the two operators & and * sequentially is redundant. So you may just write

char *path = args[1]; 

Also in general instead of the condition in the if statement

if ( args[1] == NULL) return 1; 

it will be more safer to write

if ( argc < 2 ) return 1; 
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply write:

char *path = args[1]; 

& and * operators are inverses of each other, so &* or *& can simply be removed from an expression.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.