c - 尝试返回 char 指针时出现奇怪的输出

标签 c arrays pointers

编辑:我删除了内存分配声明并将 strlen(bufferPointer) 更改为 strlen(inputLine)。这似乎摆脱了我输出中的奇怪符号。

我正在尝试编写一种方法来删除字符串中的第一个单词,并返回删除的单词的 char 指针。因为删除了这个词,字符串的大小应该会减少。

我遇到了一个奇怪的输出,我不确定为什么。

我是 C 的新手,刚刚开始熟悉指针的概念,所以任何帮助将不胜感激!

//global variables
char inputLine[] = "Hello there, my name is bob"; 
char *bufferPointer = inputLine;
char *nextWord();

main (){
    printf("%s\n", nextWord());
}

char *nextWord(){
    //calling a method that returns the number of words bufferPointer holds
    int numOfWords = nwords(bufferPointer);
    char *tmp2;

    //Allocate memory to newArray
    char *newArray = malloc(sizeof(char)*strlen(bufferPointer));

    //create backup array
    char backup[strlen(bufferPointer)];
    strncpy(backup, bufferPointer, strlen(bufferPointer));
    backup[strlen(bufferPointer)] = '\0';

    //assign newArray pointer to backup array
    newArray = backup;

    //allocate memory to token (returned variable)
    char *token = malloc(sizeof(char)*strlen(bufferPointer));
    token = strtok(newArray, " ");

    char *tmp = strchr(bufferPointer, ' ');
    //move pointer to next word
    if (tmp != NULL){
        tmp2 = tmp;
        bufferPointer = tmp +1;
    }
   return token;
}

旧的输出是:

there,
my
?²p
??
?²p?
?²p?

新的输出是:

there,
my
name
is
bob

最佳答案

strlen() 只给出字符数,不包括空字符。您还需要为空字符分配内存。

关于c - 尝试返回 char 指针时出现奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36255722/

相关文章:

c - 以整数格式存储的字节到十六进制转换

c - 基础问题 : Best Practices concerning Posix Threads and Dynamic Memory

arrays - Ruby - 按类类型对数组进行排序

c - 是否可以将指针和数组作为函数参数传递?

c# - 在另一个窗口上绘图(不闪烁?)

c - printf 和 getenv 错误 - 需要一个 char* 但参数 2 是 int 类型

arrays - 如何在java中创建一个只读数组?

javascript - 重新组织对象的javascript数组

c - 指向c中两个不同的常量结构表(查找表)的单指针

pointers - golang 和指针接收器中的自定义错误