format ’%s’ expects argument of type ’char *’

不打扰是莪最后的温柔 提交于 2019-12-05 23:36:23

There is a slight difference between char and char*. The first is a single character whereas the later is a pointer to char (which can point to variable number of char objects).

The %s format specifier really expects a C-style string, which should not only be of type char* but is also expected to be null-terminated (see C string handling). If you want to print a single character, then use %c instead.

As for the program, assuming that what I think you want is what you want, try something like this:

#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;
}

But frankly speaking, this is so fundamental that explaining might just result in writing a book on C. So you will be a lot better off if you just read one already written. For a list of good C books and resources, see The Definitive C Book Guide and List

Hope it helps. Good Luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!