【问题标题】:strlen of NULL in cc 中 NULL 的 strlen
【发布时间】:2023-03-17 17:20:01
【问题描述】:

再问一次, 我要求用小绳子做大绳子。 在我需要添加'@'的每个小字符串之间 在每个小字符串中的每个单词之间,我需要添加“#” 新字符串的开头和结尾没有任何空格

我有两个问题

  1. 我应该如何在“main”中定义大字符串以避免不必要的空格,并且不会通过插入 NULL 使 strlen 失败
  2. 定义 newLenght 的正确方法是什么?因为我不断收到负数。
void add(char** addTo, char* str,int on)
{
    //on ==1 for nun last string to add
    if (str != NULL) {
        while (str != NULL)
        {
            char* temp = strtok(str, " \n\0");
            if (temp != NULL)
            {
                int newlength = (strlen(*addTo) + strlen(temp) + 3) * sizeof(char);
                *addTo = (char*)realloc(*addTo, newlength);
                strcat(*addTo, temp);
                if (str != NULL)
                    strcat(*addTo, "#");
            }
        }
        if(on)
            strcat(*addTo, "@");
        else
            *addTo = (char*)realloc(*addTo, strlen(*addTo)-1);
    }
}

【问题讨论】:

  • 不相关:对我来说NULL 是一个指针......如果我在谈论零字符串终止符,我更喜欢明确使用'\0' 以避免混淆(对于其他人和我自己)。
  • NULLnot 一个空字符串,它甚至不是一个字符串。 ""

标签: c string char realloc strlen


【解决方案1】:

您的代码存在多个问题:

  • 函数修改str指向的数组的内容。如果str 指向字符串文字,此副作用可能会产生无法预料的后果并导致未定义的行为。

  • str 在循环中没有被修改,如果它指向一个非空的非空白字符串,则会导致无限循环。

  • 不需要on 参数。 @ 应该插入除第一个之外的每个小字符串之前,可以通过*addTo 进行测试。

  • 您没有测试重新分配失败。

这是一个修改后的版本,它使用<ctype.h> 测试所有空白字符并在每次调用时调用realloc

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

void add(char **addTo, const char *str, int on) {
    int len, newlen = 0;
    unsigned char c, lastc, first;
    char *dest;
    const char *p;

    for (p = str, lastc = ' ', first = 1; (c = *p++) != '\0'; lastc = c) {
        if (!isspace(c)) {
            if (isspace(lastc) && !first)
                newlen++;
            first = 0;
            newlen++;
        }
    }

    if (newlen == 0)
        return;

    if (*addTo && **addTo) {
        len = strlen(*addTo);
        newlen++;
    }

    dest = realloc(*addTo, len + newlen + 1);
    if (!dest) {
        perror("reallocation failure");
        abort();
    }
    *addTo = dest;
    if (len) {
        dest += len;
        *dest++ = '@';
    }
    for (p = str, lastc = ' ', first = 1; (c = *p++) != '\0'; lastc = c) {
        if (!isspace(c)) {
            if (isspace(lastc) && !first)
                *dest++ = '#';
            first = 0;
            *dest++ = c;
        }
    }
    *dest = '\0';
}

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2016-01-24
    • 2023-02-02
    相关资源
    最近更新 更多