enter image description here why the argv[1] comes with garbled words and the program runs at the segmentations fault... can't find why?

  • Could you provide the whole code?
    – RexYuan
    May 30 '15 at 10:15

Here's what you're trying to do:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char* argv[])
  int N = strlen(argv[1]);
  char key[N+1];

  int p;
  for (p = 0; p < N; p++)
    if (isalpha(argv[1][p]))
      key[p] = argv[1][p];
      return 1;
  key[p] = '\0';

  printf("key is: %s\n", key);

The thing is, when you initialize a string, say "hello", what you need to do is char foo[] = "hello" or char foo[6] = "hello" or char* foo = "hello". (If you don't get that last one it's fine for now)

So either way, foo's length is 6. If you use sizeof(foo) it'll return 6, too. Now why's that? Remember how computers construct a string? How does a computer tell that foo is a string or not, considering it's actually just all 0s and 1s underneath the hood? Computer scientists invented what's called a sentinel value to denote the end of a string, namely, NUL.(Not to be confused with NULL, which is a pointer that points to nothing) NUL is a char with all bits set to 0. That is, 0000.

NUL denotes the end of a string, and it also takes up a space because like any other char, it's 1 byte. So if you are to make a string by putting each char in individually, you must also put a '\0' at the end.

And if you're wondering, when you just write char foo[] = "hello" or char foo[6] = "hello" or char* foo = "hello", the '\0' is implicitly automatically added.

  • Thank you so much! I've shoot the bug. it works well!!
    – YING LIU
    Jun 5 '15 at 20:22
  • You can use upvote or choose it as answer so that other can also benefit from your question
    – RexYuan
    Jun 6 '15 at 4:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .