格式“%s”需要“char *”类型的参数

2024-02-18

为了锻炼我的 C 编程技能,我尝试自己编写 strncpy 函数。在这样做的过程中,我不断地遇到错误,最终解决了其中的大部分错误,但我却没有进一步的灵感继续下去。

我收到的错误是:

ex2-1.c:29:3: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
   printf("The copied string is: %s.\n", stringb);

问题是,这是一个非常常见的错误,并且它也已经在 SO 上进行了描述,只是我似乎无法应用其他人已经指出的提示。我发现我在打印变量时使用了错误的类型,当我使用 %d 格式时,它将返回一个整数,该整数可能是第一个字符的 ASCII 值,因为增加最大数量时它不会改变要复制的字节数。

使用 GDB 我发现 b 变量在完成 while 循环迭代后保存了正确的字符串,但我似乎仍然无法打印它。

我可能缺乏有关 C 语言的非常基础的知识,对于提出这个新手问题(再次),我深表歉意。如果您能提供反馈或指出我的代码中的其他缺陷,我将不胜感激。

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

void strmycpy(char **a, char *b, int maxbytes) {
  int i = 0;
  char x = 0;

  while(i!=maxbytes) {
  x = a[0][i];
  b[i] = x;
  i++;
  }

  b[i] = 0;

}


int main (int argc, char **argv) {
  int maxbytes = atoi(argv[2]);
  //char stringa;
  char stringb;
  if (argc!=3 || maxbytes<1) {
        printf("Usage: strmycpy <input string> <numberofbytes>. Maxbytes has to be more than or equal to 1 and keep in mind for the NULL byte (/0).\n");
        exit(0);
     } else {

  strmycpy(&argv[1], &stringb, maxbytes);
  printf("The copied string is: %s.\n", stringb);

  }

  return 0;
}

之间有细微的差别char and char*。第一个是单个字符,而后者是一个指向char(它可以指向可变数量的char对象)。

The %s格式说明符确实需要一个 C 风格的字符串,它不仅应该是类型char*但也预计将以空终止(参见C 字符串处理 http://en.wikipedia.org/wiki/C_string_handling)。如果你想打印单个字符,那么使用%c反而。

至于程序,假设我认为你想要的就是你想要的,尝试这样的事情:

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

static void strmycpy(char *dest, const char *src, size_t n) {
    char c;
    while (n-- > 0) {
        c = *src++;
        *dest++ = c;
        if (c == '\0') {
            while (n-- > 0)
                *dest++ = '\0';
            break;
        }
    }
}

int main(int argc, char *argv[]) {
    size_t maxbytes;
    char *stringb;

    if (argc != 3 || !(maxbytes = atoll(argv[2]))) {
        fprintf(
            stderr,
            "Usage: strmycpy <input string> <numberofbytes>.\n"
            "Maxbytes has to be more than or equal to 1 and keep "
            "in mind for the null byte (\\0).\n"
        );
        return EXIT_FAILURE;
    }

    assert(maxbytes > 0);
    if (!(stringb = malloc(maxbytes))) {
        fprintf(stderr, "Sorry, out of memory\n");
        return EXIT_FAILURE;
    }

    strmycpy(stringb, argv[1], maxbytes);
    printf("The copied string is: %.*s\n", (int)maxbytes, stringb);
    free(stringb);

    return EXIT_SUCCESS;
}

但坦率地说,这是非常基础的,解释起来可能会导致写一本关于 C 的书。所以,如果你只阅读已经写好的一本,你会好得多。有关优秀 C 书籍和资源的列表,请参阅权威 C 书指南和列表 https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list

希望能帮助到你。祝你好运!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

格式“%s”需要“char *”类型的参数 的相关文章

随机推荐