【问题标题】:C - Warning: assignment makes integer from pointer without castC - 警告:赋值从没有强制转换的指针生成整数
【发布时间】:2016-02-04 05:00:44
【问题描述】:

我正在尝试编写一个程序,将字符串的偶数和奇数索引放入它们自己的数组中(每个数组末尾都有空终止符),这些数组存储在一个数组中:

char **result = malloc(sizeof(char*) * 2);
int a, b = 0;
int index = strlen(s) / 2;
if (strlen(s) % 2 == 1) {
    result[0] = malloc(sizeof(char) * (index + 2));
    result[1] = malloc(sizeof(char) * (index + 1));
    result[0][index + 1] = "\0"; // 1
    result[1][index] = "\0";     // 2
} else {
    result[0] = malloc(sizeof(char) * (index + 1));
    result[1] = malloc(sizeof(char) * (index + 1));
    result[0][index] = "\0"; // 3
    result[1][index] = "\0"; // 4
}
for (int i = 0; i < strlen(s); i++) {
    if (i % 2 == 0) {
        result[0][a] = s[i];
        a++;
    } else {
        result[1][b] = s[i];
        b++;
    }
}
return result;

当我编译它时,注释行会收到警告“赋值从指针中生成整数而不进行强制转换”。我不明白这段代码有什么问题。帮忙?

【问题讨论】:

  • 请注意int a, b = 0;b 设置为零,但未初始化a。编译器也应该警告你。

标签: c


【解决方案1】:

在下面的作业中 -

result[0][index + 1] = "\0"; // 1
result[1][index] = "\0";     // 2

使用单引号 ' ' 而不是双引号。

"" 用于字符串文字,其中 result[1][index] 和类似的为 char ,因此,您会收到警告。

result[0][index + 1] = '\0';      /*  <-- assigning character   */ 

【讨论】:

    猜你喜欢
    • 2011-07-04
    • 1970-01-01
    • 2015-10-19
    • 2013-09-14
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多