【问题标题】:How to use a pointer in a function, in another cpp file?如何在另一个cpp文件中的函数中使用指针?
【发布时间】:2020-12-29 05:09:38
【问题描述】:

在我的 U.cpp 文件中,我在函数的指针 char 数组中赋值。然后我在我的 V.h 头文件中声明了这个函数。我想访问另一个名为 S.cpp 的 cpp 文件中的指针 char 数组中的值。如果我在 U.cpp 中使用全局变量,我可以在使用“extern”标签在头文件中声明后从 S.cpp 访问它。我无法弄清楚如何访问函数中的变量。我还需要将指针数组的值分配给 unsigned char array[];

//U.cpp
char *ipAdd[4];
char *removeSpaces(char *str)
{
    int i = 0, j = 0;
    while (str[i])
    {
        if (str[i] != ' ')
            str[j++] = str[i];
        i++;
    }
    str[j] = '\0';
    return str;
}

void dotSeperatorIP(char* y) {
    removeSpaces(y);
    char *ipAddr = y;
    char *token = strtok(ipAddr, ".");
    // Keep printing tokens while one of the 
    // delimiters present in str[].
    int i = 0;
    while (token != NULL)
    {
        ipAdd[i] = token;
        cout << ipAdd[i] << endl;
        token = strtok(NULL, ".");
        i++;
    }
}

// S.cpp
std::cout << ipAdd[0] << std::endl; // can't access, prints totally a different value

//V.h
int vimonetsetting();
void dotSeperatorIP(char*y);
char *removeSpaces(char *str);

extern char *ipAdd[];

编辑:我设法通过更改函数来访问数组。发布为答案。感谢 cmets。

【问题讨论】:

  • g++ -o output U.cpp S.cpp 应该可以工作。原因是每个 cpp 文件都被编译成它们自己的翻译单元。另一方面,当您声明一个变量 extern 时,您是在告诉编译器在另一个翻译单元中查找该变量的定义,它会在您定义它的地方找到它。这就是 extern 为您工作的原因。
  • 请提供minimal reproducible example。我不确定你在哪里包含你的标题。
  • dotSeperatorIP 中,您有一个局部变量ipAddr ,它与全局变量不同,如果有的话。
  • 我知道这些名字有点混乱。它们是不同的。 ipAddr 的行是不必要的,我猜我可以直接在 strtok 函数中使用参数。@Phil1970

标签: c++ pointers header-files local-variables


【解决方案1】:

答案:我将 dotSeperatorIP 函数更改为 char** 返回。然后,我可以通过调用函数从不同的 .cpp 文件访问数组。

char** dotSeperatorIP(char* y) {
    removeSpaces(y);
    char *ipAddr = y;
    char *token = strtok(ipAddr, ".");
    // Keep printing tokens while one of the 
    // delimiters present in str[].

    char resultArray[4];
    int i = 0;
    while (token != NULL)
    {
        ipAdd[i] = token;
        //cout << ipAdd[i] << endl;
        token = strtok(NULL, ".");
        i++;
    }

    return ipAdd;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多