【问题标题】:warning: assignment makes integer from pointer without a cast, segmentation fault警告:赋值从没有强制转换的指针生成整数,分段错误
【发布时间】:2012-03-28 19:27:29
【问题描述】:

我从 C 开始,来自 meta c 语言,基本,PHP 和 HTML 的时间很短

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

compare(const void * a, const void * b){
    return ( *(int*)a - *(int*)b );
} 

int main(){

    int arr_size = 10;

    int j;

    char array[arr_size][2];
    char str[50];
    char output[50];

    // fill the array with string and random integers
    for (j=0; j<arr_size; j++) {
         strcpy(str, "array");
         array[j][0] = str;       //i've should put *str
         array[j][1] = rand() % arr_size+1;
    }

    // print the array
    for (j=0; j<arr_size; j++) {
        strcpy(str, "");
        strcpy(output, "");
        sprintf(str, "%u", array[j][0]); // %u should be %s but return me segmentation fault
        strcat(output, str);
        strcat(output, " ");
        sprintf(str, "%i", array[j][1]);

        strcat(output, str);
        printf(output); printf("\n");
    }

    printf("\n");

}

这是完整的代码,看看

array[j][0] = str;

sprintf(str, "%u", array[j][0]);

我需要将* 放在str (*str) 之前以传递警告消息,但我没有声明任何指针。为什么是这个解决方案?

如果我将%u 更改为%s,它会返回分段错误,这是什么问题?

【问题讨论】:

  • 阅读一本关于 C 的优秀编程书籍(你会得到比在论坛上更好的解释,因为在几分钟内解释 C 是不可能的),并学会使用调试器。
  • 你能给我一些参考吗?实际上我正在使用 geany :-)
  • @sataranjasvami,见stackoverflow.com/tags/c/info
  • cprogramming.com en.wikipedia.org/wiki/The_C_Programming_Language 和 Brian W. Kernighan、Dennis M. Ritchie 的经典著作,关于C 编程语言
  • *str*(str + 0) 相同,与str[0] 相同。

标签: c multidimensional-array char printf


【解决方案1】:

array[j][0]char。您不能为其分配字符数组。 *str 只是str 中的第一个字符,所以这个赋值是有效的。

出于同样的原因,您不能使用 %s 打印它 - 此说明符用于打印以 nul 结尾的字符串,而不是单个字符。

你也不能这样做sprintf(str, "%s", array[j]);,因为它不是 nul 终止的/

【讨论】:

  • “不能分配它的字符数组”,好的。我已经使用 %c 来查看结果,好吧。我们必须通过哪种方式来解决问题?我需要字符串二维数组。
  • 您可以将指向以空结尾的char 数组的指针视为字符串。你可以使用strdup 来创建它们。顺便说一句,字符串的二维数组在 C++ 中会更容易,因为 std::vector&lt;std::string&gt; 所以 C++ 对你来说可能更容易。
  • 看来c++的字符串已经结束了,看来
猜你喜欢
  • 1970-01-01
  • 2011-07-04
  • 2015-10-19
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多