【问题标题】:Not showing only few chars when connecting strings [duplicate]连接字符串时不显示几个字符[重复]
【发布时间】:2020-02-07 14:57:46
【问题描述】:

我有一个简单的函数应该以不同的方式连接字符串。 如果我有一个字符串“abc”和另一个“123”最终字符串应该是“a1b2c3”。

这里是代码

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <stdlib.h>

char *connStrings(char *s1, char *s2) {
    int s1L, s2L,i = 0,k=1,j=0;
    s1L = sizeof(s1);
    s2L = sizeof(s2);

    char* result = (char*) malloc((s1L + s2L));
    while (s1[i] != '\0') {
        result[j] = s1[i++];
        j = j + 2;
    }
    i = 0;
    while (s2[i] != '\0') {
        result[k] = s2[i++];
        k = k + 2;
    }
    result[s1L + s2L] = '\0';
    printf("\n %s \n", result);
}

int main() {
    connStrings("abcdefghi","123456789");
}

那么问题是什么? 这个程序的最终输出还是一样的“a1b2c3d4e5f6g7h8”
它以某种方式忽略了 i 和 9 。即使我在两个字符串中添加更多字符,它仍然会打印相同的
“a1b2c3d4e5f6g7h8”。如有任何帮助或建议,我将不胜感激。

【问题讨论】:

  • sizeof(s1) 不是字符串s1 的长度。你是说strlen(s1) 吗?
  • 这将返回指针的大小,而不是字符串长度:sizeof(s1)
  • 哦,是的,这是个错误。非常感谢:)
  • 你的函数类型是char *,但你没有返回任何东西
  • 这回答了你的问题:Sizeof vs Strlen

标签: c arrays string


【解决方案1】:

使用正确的函数返回类型和strlen 而不是sizeof

#define _CRT_SECURE_NO_WARNINGS

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

void connStrings(char *s1, char *s2) {
    int s1L, s2L, i = 0, k = 1, j = 0;
    s1L = strlen(s1);
    s2L = strlen(s2);

    char *result = (char *) malloc((s1L + s2L + 1 )); // extra one for the `null` terminator `\0`
    while (s1[i] != '\0') {
        result[j] = s1[i++];
        j = j + 2;
    }
    i = 0;
    while (s2[i] != '\0') {
        result[k] = s2[i++];
        k = k + 2;
    }
    result[s1L + s2L + 1] = '\0';
    printf("\n %s \n", result);
    // free memory when you're done
    free(result);

}

int main() {
    connStrings("abcdefghi", "123456789");
    return 0; // or use void
}

【讨论】:

  • 也应该给 malloc 加 1。
  • 这里result[s1L + s2L] = '\0';也不应该是+1?
  • 我问是因为当我添加 + 1 时,它会在字符串末尾添加“=”并且我收到错误“检测到堆损坏”。 (当我 ctrc 和 ctrlv 你的代码我得到错误)但我知道我的主要问题是在 strlen 所以我将其标记为已解决)谢谢。
【解决方案2】:

当您将数组作为参数传递给函数时,您真正传递的是指向数组第一个元素的指针。

sizeof 在这种情况下不会返回缓冲区的长度,而是指针的大小。

幸运的是,C 字符串具有以空字符 ('\0') 结尾的有用属性,它允许像 strlen 这样的函数为您提供字符串的实际长度,即使您只有一个指针和不是数组。 strlen 与此类似:

size_t strlen(char *s)
{
    size_t ret = 0;
    while(*s) ret++, s++;
    return ret;
}

即使当你有一个实际数组时计算字符串的长度,你仍然不应该使用sizeof,因为这将返回缓冲区的整个大小,这可能不是其中字符串的长度。

考虑:char s[100] = "Hello World";

sizeof s 将是 100; strlen(s) 将返回 11。

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 2013-10-11
    • 1970-01-01
    • 2018-10-15
    • 2013-06-28
    • 2012-10-13
    • 2020-09-14
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多