c - 访问冲突读取位置 0x000000xx - c 结构属性 - Visual Studio

标签 c visual-studio-2008 struct access-violation

正如标题所讲述的故事。下面粘贴的是这段代码和所有依赖项。这个错误对我来说很奇怪,因为我能够在“监视”窗口中访问相同的变量,并且我找不到在运行时出现此错误的有效原因。我能找到的大多数具有相同标题的问题都与访问空地址有关,但这里的情况并非如此。 0X00000069 是无法访问的位置。我还在下面附上了“观看”窗口的屏幕截图。

typedef struct
{
    void  * variable;     // variable address
    char * signature;
    char name[30];
    char type[50];
}   GlobalVariable;

GlobalVariable VariableTable[] = 
{
    { &a, "int a = 7;", "a", "int"},
    { &ch, "char ch = 'a';", "ch", "char"},
    { NULL, NULL }
};

void PrintGlobalVariables()
{
    GlobalVariable * variable = VariableTable;
    int count = 0;
    while(variable->variable)
    {
        count++;
        variable++;
    }
    if(!count)
    {
        OutputDebugString("No global variables passed.\n");
        return;
    }
    int i = 0 ;
    variable = VariableTable;

    char       temp[MAX_PATH];
    strcpy(temp, "                                                             ");
    OutputDebugString("Global Variables = "); 
    while(variable->variable)
    {
        if(strcmp(trimwhitespace(variable->type),"int") == 0)
        {


            ////////THIS IS THE STATEMENT BELOW WHERE I AM GETTING ERROR
            wsprintf(temp, "%s=%ld",*(char *)variable->signature, *(long *)variable->variable);


        } else
        if(strcmp(trimwhitespace(variable->type),"char") == 0)
        {
            wsprintf(temp, "%s=%c", *(char *)variable->name, *(char *)variable->variable);
        }
        if((variable+1)->variable != NULL)
        {
            wsprintf(temp + strlen(temp), ",", "");
        }
        OutputDebugString(temp);
        variable++;

    }
    OutputDebugString("\n");
}
char *trimwhitespace(char *str)
{
    char *end;

    // Trim leading space
    while(isspace(*str)) str++;

    if(*str == 0)  // All spaces?
        return str;

    // Trim trailing space
    end = str + strlen(str) - 1;
    while(end > str && isspace(*end)) end--;

    // Write new null terminator
    *(end+1) = '\0';
    return str;
}

Watch Values

最佳答案

wsprintf(temp, "%s=%ld",*(char *)variable->signature, *(long *)variable->variable);

signature 字段是一个 char *。取消引用它会给出一个char。但 %s 格式说明符需要 char *。解决方法是通过删除取消引用来更改该行(并且强制转换也是不必要的)。

wsprintf(temp, "%s=%ld", variable->signature, *(long *)variable->variable);

关于c - 访问冲突读取位置 0x000000xx - c 结构属性 - Visual Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37933466/

相关文章:

c - 我可以做什么来优化以下代码?

visual-studio-2008 - 如何使用 Visual Studio 2008 Profiler 工具分析一个库解决方案?

.net - 在命令行中使用 MSBuild 重建解决方案失败,但 Visual Studio 重建工作正常

go - 打印结构体 slice 的内容

c - 在 Linux 上从 #include 生成 GCC 选项

在 C 中复制和写入 WAV 文件

c++ - 返回其自身类型的结构的结构属性

c - 如何在 C 中使用零长度数组

c - 1.#QNAN0计算标准差C时输出

visual-studio - 在 Visual Studio 任务列表中列出 javascript 任务