簡體   English   中英

警告:賦值從指針產生整數而沒有強制轉換,分段錯誤

[英]warning: assignment makes integer from pointer without a cast, segmentation fault

我從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]); ,因為它不是零終止/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM