创建一个长的缓冲区,然后将strdup放入一个新的变量中,这是保存Scanf中任何输入的最好方法吗?

问题描述 投票:0回答:1
#include <stdio.h>

int main() {
    int buf[1024];
    if (scanf("%1023[^\n]", buf) == 1) {
        int *myarray = strdup(buf);     // strdup should use malloc to dynamically allocate basing on the length of string
        if (myarray) {
            printf("Value: %s\nLength of string: %d\nDynamically allocated space: %d\n", myarray, strlen(myarray), ( (strlen(myarray) + 1)*sizeof(int) ));  // the last one should be the value of the new dyn allocated "myarray" array
            free(myarray);
        }
    }
    return 0;
}

这是避免scanf记忆问题的最好方法吗?

我可以用某种方式使用realloc来代替使用strdup和buf吗?

这个部分是否 (strlen(myarray) + 1)*sizeof(int) 正确地打印出动态分配的 myarray 用strdup?

c arrays malloc scanf realloc
1个回答
1
投票

正如我在 这另一个问题问题中的代码是一种快速和肮脏的方式来获取用户的输入,但它有一些限制。

  • 如果流有空行,它就会失败
  • 纵横捭阖 1023 字节块。
  • 它将新行留在输入流中等待处理。

getline 在POSIX系统上是可以使用的,但是如果流中存在新行,它就把新行存储在数组的最后。

下面是一个简单的实现 my_getline() 类似于 getline 但不保留换行。

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

int my_getline(char **lineptr, size_t *n, FILE *stream) {
    char *ptr = *lineptr;
    size_t size = *n;
    size_t pos = 0;
    int c;
    while ((c = getc(stream) && c != '\n') {
        if (pos + 1 >= size) {
            /* reallocate the array increasing size by the golden ratio */
            size = size + (size / 2) + (size / 8) + 16;
            ptr = realloc(ptr);
            if (ptr == NULL) {
                ungetc(c, stream);
                return EOF;
            }
            *n = size;
            *lineptr = ptr;
        }
        ptr[pos++] = c;
        ptr[pos] = '\0';
    }
    return (int)pos;
}

int main() {
    char *mystring = NULL;  // must be initialized
    size_t size = 0;        // must be initialized
    int res;

    while ((res = my_getline(&mystring, &size, stdin)) >= 0) {
        printf("Value: %s\n"
               "Length of string: %d\n",
               "Allocated size: %d\n",
               mystring, res, (int)size);
    }
    free(mystring);
    return 0;
}

关于你的最后一个问题: 这个部分 (strlen(myarray) + 1)*sizeof(int) 正确地打印出动态分配的 myarraystrdup?: 不,这个表达方式不正确,没有理由乘以? sizeof(int). 没有可移植的方法来确定由 strdup() (或 malloc),才能保证它的分配大小至少为 strlen(myarray) + 1 如果分配成功。

© www.soinside.com 2019 - 2024. All rights reserved.