我正在为C类编写程序,但是到了一个我不知道该怎么做的地步。我们正在实现一个String库类型。

我有我的头文件(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实质上指向了字符串的末尾。.您需要这样修改代码:

#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 - C指针不一致,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10864586/

10-11 21:45