小编Jac*_*row的帖子

如果不推荐使用 std::iterator ,我们还应该使用需要 std::iterator 的类或函数吗?

我听说std::iterator在 C++17 中不推荐使用。

例如,像功能<algorithm>,更可能我们要使用begin()end()它返回迭代器对象,如成员函数std::stringstd::vector等等。

或者像基于范围的 for 循环,我们需要的地方begin()以及end()返回迭代器的地方。

因此,如果std::iterator基类被弃用,我们是否应该使用成员函数,如begin()end()或使用 STL 中需要迭代器的其他函数?

c++ iterator for-loop c++17

9
推荐指数
2
解决办法
329
查看次数

将结构成员指针分配给另一个动态内存分配的指针是否安全?

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

struct Test {
    const char *str;
};

void test_new(Test *test) {
    char *s = malloc(100);
    
    s[0] = 'H';
    s[1] = 'i';
    s[2] = '\0';
    
    test->str = s;
}

int main(void) {
    struct Test test;
    
    test_new(&test);
    
    puts(test.str);
    free(test.str);
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是允许的吗?将结构成员分配给函数中的局部变量(字符指针)test_new?(被test->str = s允许?)

我听说数组变量本来就是局部变量,但在函数结束后会被释放。我想知道这是否适用于分配内存的局部变量。

像这样:

char *test(void) {
    char s[100];
    return s;
}
Run Code Online (Sandbox Code Playgroud)

s将在函数结束时消失,所以我想知道这是否适用于我的结构,特别是我不是返回,而是更改成员。

test->str将结构成员指针(即)分配给另一个动态内存分配的指针(即)是否安全s

c memory struct pointers scope

5
推荐指数
2
解决办法
179
查看次数

头文件中的“...”参数是否需要包含 stdarg.h ?

#ifndef WHATEVER_H
#define WHATEVER_H

void test(const char *format, ...); // would you have to #include <stdarg.h> for ... on argument, or is it ok if you don't use it

#endif // WHATEVER_H
Run Code Online (Sandbox Code Playgroud)

因此,如果我有一个像这样的头文件,我需要将其...作为我的void test函数的参数,我是否必须包含 stdarg.h 作为...参数,或者它不是强制性的?

c arguments header-files variadic-functions

4
推荐指数
1
解决办法
529
查看次数

为什么将文件指针分配给结构指针成员会导致分段错误?

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

typedef struct CCSV {
    FILE *file;
} CCSV;

CCSV *csv_open(char *filename) {    
    CCSV *csv;

    csv->file = fopen(filename, "r");

    if (csv->file == NULL)
        return NULL;

    return csv;
}

int main(void) {
    CCSV *csv = csv_open("cars.csv");

    if (csv == NULL) {
        puts("CSV File doesn't exist.");
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

具体用csv_open的功能,我想指定csv->filefopen(filename, "r"),但它造成分段错误。我一直在网上搜索并试图解决这个问题,但没有任何效果。

为什么将文件指针分配给结构指针成员会导致分段错误?

c pointers

1
推荐指数
1
解决办法
44
查看次数

Why is the compiler giving a warning that a pointer may be uninitialized when it's going to be initialized and won't the pointer update?

    char *s, *p = s;
    size_t len = 0;

    while (str[len++]);

    s = malloc(sizeof(*s) * (len + 1));
Run Code Online (Sandbox Code Playgroud)

How come here: char *s, *p = s; gives warning, but s is going to be initialized with malloc later.

chl/string.c:9:15: warning: ‘s’ may be used uninitialized in this function [-Wmaybe-uninitialized]
    9 |     char *s, *p = s;
                      ^
Run Code Online (Sandbox Code Playgroud)

Since p is a pointer, pointing to s, won't p be updated as well when it points to s when s will be …

c memory pointers

1
推荐指数
1
解决办法
111
查看次数