【问题标题】:Check chars in a string while using pointers使用指针检查字符串中的字符
【发布时间】:2020-06-14 17:38:15
【问题描述】:

我想检查字符串中的每个单独的字符。字符串存储在指针中。 由于某种原因我不能,它只会让我得到整个字符串。 这是我的代码:

int main() {
  char *s=(char*)calloc(30,sizeof(char));
  s="hello";
  printf("%s",&s[2]);
  return 0;
 }

此代码打印“llo”,我只需要 1 个字符,如“l”或“o”。 有谁知道我怎么能实现它? 太棒了

【问题讨论】:

  • Printf 字符不是字符串。查找 printf 的格式代码,并问自己如果不使用“&”,s[2] 的值是多少。
  • 您还丢失了使用calloc 创建的块(内存泄漏)。 检查每个单独的字符是什么意思?
  • printf("%c",s[2]);
  • 尝试使用 strcpy,设置 s 指向 "hello" 与复制字符串不同。
  • 检查每个单独的字符,我的意思是如果我想找到字母“l”或者检查所有字符串是数字还是没有数字字符串。

标签: c string pointers


【解决方案1】:

使用%c 转换说明符来打印一个单一的character 而不是%s 来打印一个字符串

calloc() 分配的内存也是无用的,因为指向 char s 的指针是由字符串文字 "hello" 的第一个元素的地址分配的。

#include <stdio.h>

int main (void) 
{
    const char *s = "hello";
    printf("%c", s[2]);
    return 0;
}

输出:

l

旁注:

  • 使用const 限定符来防止对导致undefined behavior 的字符串文字的任何无意写入尝试。

如果要分配内存并通过字符串文字"hello" 分配/初始化分配的内存,请使用strcpy()(标题string.h):

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

int main (void) 
{
    char *s = calloc(30, sizeof(*s));
    if (!s)      // Check if allocation failed.
    {
        fputs("Error at allocating memory!", stderr);
        exit(1);
    }
    strcpy(s, "hello");
    printf("%c", s[2]);
    return 0;
}

输出:

l

或者您可以使用strdup()(注意:strdup() 不是标准 C 库的一部分),它将使用作为参数初始化的字符串文字的字符串自动分配内存:

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

int main (void) 
{
    char *s = strdup("hello");
    if (!s)            // Check if allocation failed.
    {
        fputs("Error at allocating memory!", stderr);
        exit(1);
    }

    printf("%c", s[2]);
    return 0;
}

旁注:

“字符串存储在指针中。”

这样的事情是不可能的。指针指向字符串的第一个元素(字面量)。指针不存储字符串。

【讨论】:

  • 甚至 strdup("Hello")
  • @pm100 问题是strdup() 不是标准的一部分。我也不确定OP是否只为字符串文字"hello"分配内存。然后他/她不会分配30char 元素的缓冲区,而只会分配6 char 的缓冲区。相当神秘的代码,很难。
  • strdup 是 posix 标准
  • @pm100 将其纳入答案。谢谢。之前也有点缺席。如果需要,OP 当然可以realloc() malloc。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-10
  • 1970-01-01
  • 2020-10-30
  • 2020-06-11
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多