Am I creating two separate pointers here, or am I properly calling for a single memory address that is the commands?

Viewed 55

To specify my question, am I referencing the the commands in int main directly when using the function, or am I copying them, and then referencing those copies using the function? I'm having trouble understanding pointers, and strings in C.

Also, if I'm doing this error checking in a really stupid way, and you know how it could be better, I'd love to be enlightened. I'm coming from Python, and am still learning C to a large extent. My goal currently is to write a very minimal compiler that will do simple addition.

#include <stdio.h>

int CompilationErrorChecking(int argc, char *argv[]){
  // Check initialy if for at least one argument attatched to Iwa
  if (argc < 2 && argc == 1){
    printf("Error: No arguments found");
  // If the arguments are correct: Iwa_Compiler <FileName>
  // Execute, and say the command back to them
  } else if (argc <= 2){
    printf("%s %s\n", argv[0], argv[1]);
  // If there are more than 2 arguments, spit error
  } else {
    printf("Erorr: Too many arguments");
  }
  return 0;
}

int main(int argc, char *argv[]) {
  CompilationErrorChecking(argc, argv);
  return 0;
}
2 Answers

First of all you are copying the value as you are using pointer. Secondly, your if statement:

if(value<2 && value==1)

you can change this to

if(value==1)
int CompilationErrorChecking(int argc, char *argv[]) {
  ...
}

int main(int argc, char *argv[]) {
  CompilationErrorChecking(argc, argv);
  ...
}

You are passing argc and argv to the helper function correctly. What you've written passes the count argc and the pointer argv, which are both cheap copies, and does not do any expensive string copying. (It's actually hard to accidentally do an expensive copy. You would have to explicitly call strcpy(), memcpy(), or other similar function.)

if (argc < 2 && argc == 1){
  printf("Error: No arguments found");
// If the arguments are correct: Iwa_Compiler <FileName>
// Execute, and say the command back to them
} else if (argc <= 2){
  printf("%s %s\n", argv[0], argv[1]);
// If there are more than 2 arguments, spit error
} else {
  printf("Erorr: Too many arguments");
}

While we're here, it's worth pointing out that these argc checks aren't right. For the first one you want to error out when there are no arguments, which happens when argc < 2 or argc <= 1 (these are equivalent). The extra && argc == 1 isn't helping.

For the second one, you should either be checking that argc == 2. The <= is misleading since that else if block would actually fail if argc were less than 2.

Related