我交叉發帖,因爲它可能是一個Pd問題,但也許有人在這裏知道爲什麼會發生這樣的事情。古怪:指針地址不會改變,但內容不會改變1
簡而言之,我有一個dll,我在一個名爲Pd(puredata,用於計算機音樂)的程序中使用。我創建了一個名爲recordString的對象,我將它與基本的Pd API一起使用來創建pd將讀取的dll。所有Pd需要訪問的都是一些簡單的功能。我已經使recordString成爲使用Pd API的代碼的一部分。
無論如何,recordString對象包含一個char *,我使用new創建(我也試過malloc)。當我設置char *的值時,它將正確設置爲HELLOWORLD。我輸出地址以確保它保持在應該的位置。
我已經確認該值是應該如此,除了稍後當我調用函數來獲取char *的值時,它已經以某種方式被移動了1個字節。
有沒有人聽說過指針將地址值改爲1的情況?沒有被告知?
總之,這裏的輸出,並遵循對於datarecord.cpp代碼
string: HELLOWORLD length: 10 address: 32774028 address-2: 32578488 calling postString string: ELLOWORLD length: 9 address: 32774028 address-2: 32578489
#include "m_pd.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "datarecord.h"
using namespace std;
recordString::recordString()
:name(NULL)
{
};
recordString::recordString(const char* sourceString)
{
this->name = new char[strlen(sourceString)+1];
post("-------- in string constructor -----------");
post("address: %d", &this->name);
strcpy(this->name, sourceString);
post("copy: %s", this->name);
};
recordString::~recordString()
{
//delete(this->name);
delete[] name;
name = NULL;
//free(this->name);
};
recordString::recordString(const recordString & rhs)
{
post("-------- in copy constructor -----------");
post("source: %s", rhs.name);
post("length: %d", strlen(rhs.name));
post("\n");
this->name = new char[strlen(rhs.name)+1];
strcpy(this->name, rhs.name);
post("copy: %s", this->name);
post("length: %d", strlen(this->name));
post("address: %d", &name);
post("address-2: %d", name);
post("\n");
}
recordString & recordString::operator=(const recordString &rhs)
{
post("-------- in operator= -----------");
post("source: %s", rhs.name);
post("length: %d", strlen(rhs.name));
post("\n");
if(name!=NULL)
{
delete[] name;
}
//this->name = (char*) malloc((strlen(rhs.name)));
this->name = new char[strlen(rhs.name)+1];
strcpy(this->name, rhs.name);
post("copy: %s", this->name);
post("length: %d", strlen(this->name));
post("address: %d", &name);
post("address-2: %d", name);
post("\n");
}
int recordString::setString(const char * sourceString)
{
post("-------- in setString -----------");
post("source: %s", sourceString);
post("length: %d", strlen(sourceString));
post("\n");
this->name = new char[strlen(sourceString)];
strcpy(this->name, sourceString);
post("copy: %s", this->name);
post("length: %d", strlen(this->name));
post("address: %d", &name);
post("address-2: %d", name);
post("\n");
return (this->name == NULL);
}
void recordString::postString()
{
post("string: %s", this->name);
post("length: %d", strlen(this->name));
post("address: %d", &name);
post("address-2: %d", name);
post("\n");
}
注意你的賦值運算符重載應該返回一些東西。 – 2013-04-06 20:57:13
這是C++,而不是C(你有類)。在這種情況下,使用'std :: string'會爲你節省很多的工作,並且可能會加快你的代碼速度。 – Cameron 2013-04-06 20:57:20
要繼續@Cameron的評論,使用標準庫來處理任何事物(通用集合,泛型算法和其他事物的** lot **)將顯着簡化您作爲C++程序員的生活! – 2013-04-06 21:03:06