gpt4 book ai didi

C 指针不一致

转载 作者:行者123 更新时间:2023-12-02 07:57:10 24 4
gpt4 key购买 nike

我正在为 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com