私は 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 を指しているにもかかわらず、それらのバッファーが異なるメモリ アドレスを指していることです。何故ですか?
前もって感謝します