C中的字符串(分段错误)

时间:2017-03-30 23:20:11

标签: c string segmentation-fault

我想生成随机字符串的每个人这是我的代码, 控制台显示我的段错误。我不明白为什么.. 有代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(int argc, char const *argv[]) {
  int n;
  char k,str[5];
  srand(time(NULL));
  strcpy(str,k);
  n = rand()%25+1;
  for (int i = 0; i < 3; i++) {
    n = rand()%25+1;
    if (isalpha(n+97)) {
      k = (char)n+97;
      strcat(str,k);
      printf("%c\n",k);
      //strcpy(str,"hellp");
    }
  }
  puts(str);
  return 0;
}
//97-122

我很抱歉英语不好

1 个答案:

答案 0 :(得分:0)

正如lurker指出的那样:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(int argc, char const *argv[]) {
  int n;
  char k;
  /*
  strcat expect a pointer on char, and not a const pointer,
  when you declare str[] it is a const...
  */
  char * str = malloc(5 * sizeof(char));
  srand(time(NULL));
  // strcpy(str,k); //why do you want to do this ?
  n = rand()%25+1;
  int i = 0;
  for (i = 0; i < 3; i++) {
    n = rand()%25+1;
    if (isalpha(n+97)) {
      k = (char)n+97;
      /*
      strcat expect a pointer, so use &k, but strcat expect str 
      and not only char so you gonna have \0 end str missing
      */
      strcat(str, &k);
      printf("%c\n", k);
    }
  }
  puts(str);
  return 0;
}
//97-122

如果您不希望\0缺少符号,请替换

strcat(str, &k);

通过

sprintf(str, "%s%c", str,k); //%s for the string, and %c for the char

欢迎您对我的英语或/和C的所有评论。