c - 警告 : assignment makes integer from pointer without a cast, 段错误

标签 c multidimensional-array char printf

我从 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,它会返回段错误,这是什么问题?

最佳答案

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

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

您也不能执行 sprintf(str, "%s", array[j]);,因为它不是以 nul 结尾的/

关于c - 警告 : assignment makes integer from pointer without a cast, 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666361/

相关文章:

c - 错误 : Misplace Else

java - 使用递归检查周围的单元格

c++在win32学校应用程序上构建错误

c++ - 如何将 char* 插入到 map<string,string> 中?

c - 我正在尝试使用 C 编码从 linux 制作 uniq 命令

c - Arinc429 32 位字

c - 如何让gdb跟随execv?不工作尽管 "follow-exec-mode"

java:将一个值添加到二维数组中的一列

c - 指针声明/引用后的方括号

c# - 检查大数是否是有效的 Unicode 字符