【问题标题】:Printing out values using pointers使用指针打印出值
【发布时间】:2011-09-12 00:25:54
【问题描述】:

我有一些不确定数量的变量及其计数的排序数组。我需要像这样构建一个字符串:

Attribute[0]: p=2, e=8

我的问题是数组实际上是一个指针,我不想使用固定长度的循环,所以我看到的唯一解决方案是使用数组指针。

void printArray(Node_ptr node){
    int count=0; //character count
    char *temp= node->attributes; //duplicate attribute array

    char cur; //current char
    char *outputCat= emalloc(150); //concatenate counts to a single string

    strcpy(outputCat, "Attribute %d counts are: ");
    qsort(temp, lineCount, sizeof(char), compare); //sort the array

    while ((temp) != NULL){
        cur= *temp;
        ++temp;
        if (strcmp(&cur, temp)==0) //if characters are same
            count++; 
        else { //build reporting string
            strcat(outputCat, &cur);
            strcat(outputCat, "= ");
            sprintf(outputCat, "%d  ", count);
            count=0;
        }
    }
    free(outputCat);
}

这里的问题是strcmp(&cur, ++temp)==0 每次都返回 false,即使我在调试器中看到它们的值也是如此。正因为如此,else 条件不断被构建,并在多次迭代后引发段错误。

两个问题:

1- 即使输入相同的值,什么可以使strcmp 返回非零值? 2- 我可以做些什么来修复代码?

【问题讨论】:

  • 您不应该在char 上使用strcmp 或strcat。两个参数都必须是 NULL 终止的字符数组。这本身就可能导致段错误。事实上,如果修复它可以完全修复您的代码,我不会感到惊讶。
  • 大脑放屁。我忘了字符可以直接比较,不用函数。然而,改变并没有做任何事情,因为比较总是被跳过,即使cur是'e',*temp也是如此
  • 好吧,这就是答案,不是吗?您应该重新提交作为答案,以便 Jason 可以接受。
  • 更新您的代码,以便我们可以看到仍然无法正常工作的部分。

标签: c segmentation-fault strcmp


【解决方案1】:

在你的行中:

strcmp(&cur, temp)

cur 是在本地声明的char,因此,&cur 只是堆栈上的某个位置,在这种情况下毫无意义。

我相信您的意思是检查当前字符 cur 是否与下一个字符 *temp 相同。
这看起来像:

if (cur == *temp) //if characters are same
    count++; 

接下来,我将着眼于大幅简化您的输出部分:

sprintf(outputCat, "%c = %d", *cur, count);  // e.g.   "e = 8"
count=0;

最后,我怀疑您的循环是否会终止,因为它会继续执行 temp++,而 temp != NULL。
我相信您打算检查存储在指针 temp 处的 VALUE。
*temp 应该正确地检查 '\0',而不是 NULL。
(\0 和 NULL 恰好具有相同的值,但它们应该不在语义上被视为相同)

while (*temp != '\0'){

P.S. 您的简单但出色的评论“// 如果字符相同”对我理解您的代码非常有帮助。这是 INVALUABLE 的短而有意义的 cmets 的极好例子。谢谢。


(希望是最终编辑)
总的来说,我建议的更改如下所示:

void printArray(Node_ptr node){
    int count=0; //character count
    char *temp= node->attributes; //duplicate attribute array

    char cur; //current char
    char *outputCat= emalloc(150); //concatenate counts to a single string

    strcpy(outputCat, "Attribute %d counts are: ");
    qsort(temp, lineCount, sizeof(char), compare); //sort the array

    while (*temp != '\0'){
        cur= *temp;
        ++temp;
        if (cur == *temp) //if characters are same
            count++; 
        else { //build reporting string
            sprintf(outputCat, "%c = %d", *cur, count);  // e.g.   "e = 8"
            count=0;
        }
    }
    free(outputCat);
}

你觉得怎么样?

【讨论】:

  • `cur==*temp) 行是关键。现在,我要做一些更改,因为唯一数据点的数量因数组而异。使用我的原始代码和这个代码,它适用于第一组值,但如果 cur 从 e 更改为 p,则代码不会针对它进行调整。
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 2012-03-03
  • 1970-01-01
相关资源
最近更新 更多