Programing

C에서 char ** argv 또는 char * argv []를 사용해야합니까?

lottogame 2020. 7. 13. 08:07
반응형

C에서 char ** argv 또는 char * argv []를 사용해야합니까?


나는 단지 C를 배우고 있으며 주요 방법으로 사용해야하는 것이 무엇인지 궁금합니다. 차이점이 있습니까?

편집 : 그렇다면 어느 것이 더 일반적입니까?


C를 배우는 동안 일반적인대신 배열과 포인터 차이점 을 먼저 이해하는 것이 좋습니다 .

매개 변수 및 배열 영역에는 몇 가지 혼란스러운 규칙이 있으므로 계속 진행해야합니다. 먼저 매개 변수 목록에서 선언 한 내용은 특별하게 취급됩니다. C에서 함수 매개 변수로 이해가되지 않는 상황이 있습니다.

  • 매개 변수로서의 기능
  • 매개 변수로서의 배열

매개 변수로서의 배열

두 번째는 즉시 명확하지 않을 수 있습니다. 그러나 배열 차원의 크기가 C의 유형의 일부라고 생각할 때 명확합니다 (차원 크기가 주어지지 않은 배열은 유형이 불완전합니다). 따라서 값을 기준으로 배열을 가져 오는 함수 (복사본을받는 함수)를 만들면 한 가지 크기에 대해서만 가능합니다! 또한 배열이 커질 수 있으며 C는 가능한 한 빨리 노력합니다.

C에서는 이러한 이유로 배열 값 이 존재하지 않습니다. 배열의 값을 얻으려면 대신 배열의 첫 번째 요소에 대한 포인터입니다. 그리고 여기에 실제로 해결책이 있습니다. C 컴파일러는 유효하지 않은 배열 매개 변수를 그리는 대신 각 매개 변수의 유형을 포인터로 변환 합니다. 이것을 기억하십시오, 그것은 매우 중요합니다. 매개 변수는 배열이 아니라 대신 해당 요소 유형에 대한 포인터입니다.

이제 배열을 전달하려고하면 대신 전달되는 것은 배열의 첫 번째 요소에 대한 포인터입니다.

소풍 : 매개 변수로 기능

완성을 위해, 이것이 문제를 더 잘 이해하는 데 도움이 될 것이라고 생각하기 때문에 매개 변수로 함수를 사용하려고 할 때 업무 상태가 무엇인지 살펴 보겠습니다. 실제로, 먼저 이해가되지 않습니다. 매개 변수는 어떻게 함수가 될 수 있습니까? 물론, 우리는 그 장소에서 변수를 원합니다! 따라서 컴파일러가 발생할 때 수행하는 작업은 다시 함수를 함수 포인터변환 하는 것 입니다. 함수를 전달하려고하면 해당 함수에 대한 포인터가 대신 전달됩니다. 따라서 다음은 동일합니다 (배열 예제와 유사).

void f(void g(void));
void f(void (*g)(void));

괄호 *g가 필요합니다. 그렇지 않으면 반환하는 함수 void*에 대한 포인터 대신 반환하는 함수를 지정합니다 void.

배열로 돌아 가기

이제 처음에는 배열에 불완전한 유형이있을 수 있다고 말했습니다. 아직 크기를 지정하지 않으면 발생합니다. 우리는 이미 배열 매개 변수가 존재하지 않지만 대신 배열 매개 변수가 포인터라는 것을 알았으므로 배열의 크기는 중요하지 않습니다. 즉, 컴파일러는 다음을 모두 번역하며 모두 동일합니다.

int main(int c, char **argv);
int main(int c, char *argv[]);
int main(int c, char *argv[1]);
int main(int c, char *argv[42]);

물론 크기를 넣을 수있는 것은 이치에 맞지 않으며 그냥 버려집니다. 이러한 이유로 C99는 그 숫자에 새로운 의미를 부여했으며 대괄호 사이에 다른 것들이 나타날 수 있습니다.

// says: argv is a non-null pointer pointing to at least 5 char*'s
// allows CPU to pre-load some memory. 
int main(int c, char *argv[static 5]);

// says: argv is a constant pointer pointing to a char*
int main(int c, char *argv[const]);

// says the same as the previous one
int main(int c, char ** const argv);

The last two lines say that you won't be able to change "argv" within the function - it has become a const pointer. Only few C compilers support those C99 features though. But these features make it clear that the "array" isn't actually one. It's a pointer.

A word of warning

Note that all i said above is true only when you have got an array as a parameter of a function. If you work with local arrays, an array won't be a pointer. It will behave as a pointer, because as explained earlier an array will be converted to a pointer when its value is read. But it should not be confused with pointers.

One classic example is the following:

char c[10]; 
char **c = &c; // does not work.

typedef char array[10];
array *pc = &c; // *does* work.

// same without typedef. Parens needed, because [...] has 
// higher precedence than '*'. Analogous to the function example above.
char (*array)[10] = &c;

You could use either, it depends how you want to use it. char* argv[] is (mostly) equivalent to char ** argv. Both forms are pointer to pointers to char, the only difference is that with char *argv[] you are informing the compiler that the value of argv won't change (though the values it points to still can). Actually, I'm wrong, they're completely equivalent. See litb's comments and his answer.

It really depends how you want to use it (and you could use either in any case):

// echo-with-pointer-arithmetic.c
#include <stdio.h>
int main(int argc, char **argv)
{
  while (--argc > 0)
  {
    printf("%s ", *++argv);
  }
  printf("\n");
  return 0;
}

// echo-without-pointer-arithmetic.c
#include <stdio.h>
int main(int argc, char *argv[])
{
  int i;
  for (i=1; i<argc; i++)
  {
    printf("%s ", argv[i]);
  }
  printf("\n");
  return 0;
}

As for which is more common - it doesn't matter. Any experienced C programmer reading your code will see both as interchangeable (under the right conditions). Just like an experienced English speaker reads "they're" and "they are" equally easily.

More important is that you learn to read them and recognize how similar they are. You'll be reading more code than you write, and you'll need to be equally comfortable with both.


You can use either of the two forms, as in C arrays and pointers are interchangeable in function parameter lists. See http://en.wikipedia.org/wiki/C_(programming_language)#Array-pointer_interchangeability.


It doesn't make a difference, but I use char *argv[] because it shows that is a fixed size array of variable length strings (which are usually char *).


It doesn't really make a difference, but the latter is more readable. What you are given is an array of char pointers, like the second version says. It can be implicitly converted to a double char pointer like in the first version however.


char ** → pointer to character pointer and char *argv [] means array of character pointers. As we can use pointer instead of an array, both can be used.


you should declare it as char *argv[], because of all the many equivalent ways of declaring it, that comes closest to its intuitive meaning: an array of strings.


I see no special merit of using either approach instead of the other -- use the convention that is most in line with the rest of your code.


If you'll need a varying or dynamic number of strings, char** might be easier to work with. If you're number of string is fixed though, char* var[] would be preferred.


I know this is outdated, but if you are just learning the C programming language and not doing anything major with it, don't use command-line options.

If you are not using command line arguments, don't use either. Just declare the main function as int main() If you

  • Want the user of your program to be able to drag a file onto your program so that you can change the outcome of your program with it or
  • Want to handle command-line options(-help, /?, or any other thing that goes after program name in terminal or command prompt)

use whichever makes more sense to you. Otherwise, just use int main() After all, if you end up wanting to add command-line options, you can easily edit them in later.

참고URL : https://stackoverflow.com/questions/779910/should-i-use-char-argv-or-char-argv-in-c

반응형