C 指针不一致

标签 c pointers

我正在为 C 类编写一个程序,但我已经到了不知道该怎么办的地步。我们正在实现一个字符串库类型。

我有我的头文件(MyString.h)

typedef struct {
    char *buffer;
    int length;
    int maxLength;
} String;

String *newString(const char *str);

实现函数的文件(MyString.c)

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

String *newString(const char *str) {

// Allocate memory for the String
String *newStr = (String*)malloc(sizeof(String));

if (newStr == NULL) {
    printf("ERROR: Out of memory\n");
    return NULL;
}   

// Count the number of characters
int count;
for (count = 0; *(str + count) != '\0'; count++);
count++;

// Allocate memory for the buffer
newStr->buffer = (char*)malloc(count * sizeof(char));

if (newStr->buffer == NULL) {
    printf("ERROR: Out of memory\n");
    return NULL;
}

// Copy into the buffer
while (*str != '\0')
    *(newStr->buffer++) = *(str++);
*(++newStr->buffer) = '\0';

// Set the length and maximum length
newStr->length = count;
newStr->maxLength = count;

printf("newStr->buffer: %p\n",newStr->buffer); // For testing purposes

return newStr;
}

和一个测试器(main.c)

#include <stdio.h>
#include "MyString.h"

main() {
char str[] = "Test character array";

String *testString = newString(str);

printf("testString->buffer: %p\n",testString->buffer); // Testing only
}

问题是,即使 testString 指向在 newString() 中创建的 String,它们的缓冲区也指向不同的内存地址。这是为什么?

提前致谢

最佳答案

通过使用 *(++newStr->buffer)*(newStr->buffer++),您将移动 newStr->buffer code> 实质上指向字符串的末尾。您需要这样修改代码:

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

String *newString(const char *str) {
    // Allocate memory for the String
    String *newStr = (String*)malloc(sizeof(String));

    if (newStr == NULL) {
        printf("ERROR: Out of memory\n");
        return NULL;
    }

    // Count the number of characters
    int count;
    for (count = 0; *(str + count) != '\0'; count++);
    count++;

    // Allocate memory for the buffer
    newStr->buffer = (char*)malloc(count * sizeof(char));

    if (newStr->buffer == NULL) {
        printf("ERROR: Out of memory\n");
        return NULL;
    }

    char *pBuffer = newStr->buffer; // don't move newStr->buffer, have another pointer for that.

    // Copy into the buffer
    while (*str != '\0')
        *(pBuffer++) = *(str++);
    *pBuffer = '\0';

    // Set the length and maximum length
    newStr->length = count;
    newStr->maxLength = count;

    printf("newStr->buffer: %p\n", newStr->buffer); // For testing purposes

    return newStr;
}

关于C 指针不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10864586/

相关文章:

c - 阿托到底怎么了?

c - 你可以在 double 中存储多大的数字,在 c 中用 float 存储?

c - 如何从 xml schema(xsd) 的复杂类型获取正则表达式?

c - C 的一元 '&' 有什么作用?为什么它不适用于常量?

c - GNU ld 不能与 libboost 静态链接,但可以动态链接

c++ - 当 ParamType 既不是指针也不是引用时自动类型推导

c++ - 运算符[]处理指针时的内部逻辑

javascript - 如何删除 Javascript 中的所有对象引用?

c++ - 指针和面向对象编程

c - 从句子(字符串)中删除一个词