0

我正在编写一个normalize准备处理字符串的函数。这是代码:

/* The normalize procedure examines a character array of size len 
 in ONE PASS and does the following:
 1) turns all upper-case letters into lower-case ones
 2) turns any white-space character into a space character and, 
 shrinks any n>1 consecutive spaces into exactly 1 space only
 3) removes all initial and final white-space characters

 Hint: use the C library function isspace() 
 You must do the normalization IN PLACE so that when the procedure
 returns, the character array buf contains the normalized string and 
 the return value is the length of the normalized string.
  */
 int normalize(char *buf, /* The character array containing the string to be normalized*/
            int len    /* the size of the original character array */)
 {
    /* exit function and return error if buf or len are invalid values */
if (buf == NULL || len <= 0)
  return -1; 

char *str = buf; 
char prev, temp; 
len = 0; 

/* skip over white space at the beginning */
while (isspace(*buf))
  buf++; 


/* process characters and update str until end of buf */
while (*buf != '\0') {
  printf("processing %c, buf = %p, str = %p \n", *buf, buf, str); 

  /* str might point to same location as buf, so save previous value in case str ends up changing buf */
  temp = *buf; 

  /* if character is whitespace and last char wasn't, then add a space to the result string */
  if (isspace(*buf) && !isspace(prev)) {
    *str++ = ' '; 
    len++; 
  } 

  /* if character is NOT whitespace, then add its lowercase form to the result string */
  else if (!isspace(*buf)) {
    *str++ = tolower(*buf); 
    len++; 
  }

  /* update previous char and increment buf to point to next character */
  prev = temp; 
  buf++; 
}


/* if last character was a whitespace, then get rid of the trailing whitespace */ 
if (len > 0 && isspace(*(str-1))) {
  str--; 
  len--; 
}

/* append NULL character to terminate result string and return length */
*str = '\0'; 
return len;

}

但是,我遇到了分段错误。我已将问题缩小到这一行:

*str++ = *buf;

更具体地说,如果我尝试尊重 str 并为其分配一个新的 char 值(例如:)*str = c,程序将崩溃。但是str在开始时被初始化指向buf所以我不知道为什么会这样。

*编辑:这就是我调用函数的方式:* char *p = "string goes here"; normalize(p, strlen(p));

4

2 回答 2

1

您不能使用pwhenp被声明为来调用您的函数char *p = "Some string";,因为p它是一个初始化为字符串常量的指针。这意味着您不能修改 的内容p,并且尝试这样做会导致未定义的行为(这是段错误的原因)。但是,您当然可以p指向其他地方,即指向可写字符序列。

或者,您可以声明p为一个字符数组。您可以像使用指针声明一样对其进行初始化,但数组声明使字符串可写:

char p[] = "Some string";
normalize(p, strlen(p));

请记住,数组不是可修改的左值,因此您将无法分配给p,但您可以更改 中的内容p[i],这正是您想要的。

除此之外,请注意您的代码prev在第一次循环迭代中使用垃圾值,因为您从未初始化它。因为你只prev用来测试它是否是一个空格,也许更好的方法是有一个 flag prev_is_space,而不是显式存储前一个字符。这将使启动循环变得容易,prev_is_space如果有前导空格,您只需初始化为 0 或 1(这实际上取决于您希望函数的行为方式)。

于 2013-10-25T22:48:31.050 回答
0

在 isspace(prev) 中使用它之前,我没有看到你在哪里初始化 prev。

于 2013-10-25T22:45:43.820 回答