调试器向指针显示错误的值

我有以下代码:

#include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include  #include using namespace std; char str[] = "this.is.a.test"; char str2[] = "this.is.another.test"; typedef struct { size_t count; char** strings; } Tokens; Tokens Tokenize(char* String, char Split) { Tokens t; t.count = 1; for (size_t i = 0; String[i] != 0; i++) { if (String[i] == Split) t.count++; } t.strings =(char**) malloc(sizeof(char*)* t.count); if (t.count > 0) t.strings[0] = String; for (size_t i = 0, j = 1; String[i] != 0; i++) { if (String[i] == Split) { t.strings[j] = &String[i + 1]; String[i] = 0; j++; } } return t; } int main(void) { Tokens t = Tokenize(str, '.'); printf("number of strings: %i\n---\n", t.count); for (size_t i = 0; i < t.count; i++) { printf("%i: %s\n", i, t.strings[i]); } free(t.strings); } 

问题是当我调试代码时,特别是那行t.strings[j] = &String[i + 1];

在this.is.a.test的测试用例中

在第一个发现点。 ,它应指向此,但在调试器中它显示以下图片。 在此处输入图像描述 在此处输入代码

调试器显示的内容在第55行是正确的。已经进行了赋值,因此t.strings[j]指向点后面。

请注意,在Tokenize您分配了Tokens t; 在堆栈上,然后返回此t 。 那很糟糕(非常糟糕!)。 因为t在堆栈上,所以它将被printf调用覆盖。

(虽然大多数是C,但正式它是C ++,因为在C中你不能在for初始化中声明一个变量,如for (size_t i = 0;