2012-03-12 50 views
2

我開始用C,從元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]); 

我需要前把傳遞警告消息,但我沒有聲明任何指針。爲什麼要這個解

如果我改變%u%s它返回我分段錯誤,有什麼問題?

+2

閱讀一個良好的編程書約C(你會得到一個更好的解釋,比上一個論壇,因爲在幾分鐘內解釋C是不可能),並學會使用調試器。 – 2012-03-12 11:43:33

+0

你能建議我一些參考嗎?其實我使用geany :-) – DreamIt 2012-03-12 11:47:52

+1

@sataranjasvami,請參閱http://stackoverflow.com/tags/c/info – 2012-03-12 11:49:03

回答

0

array[j][0]char。你不能分配它的字符數組。 *str只是str中的第一個字符,所以這個賦值是有效的。

出於同樣的原因,您不能用%s打印它 - 此說明符用於打印nul終止的字符串,而不是單個字符。

你也不能這樣做sprintf(str, "%s", array[j]);,因爲它不是空終止/

+0

」不能指定它的字符數組「,好的。我用%c來查看結果,好吧。我們需要通過哪種方式解決問題?我需要字符串二維數組。 – DreamIt 2012-03-12 12:09:02

+0

您可能會考慮一個指向以char爲空字符串的空字符結尾數組的指針。你可以使用'strdup'來創建它們。順便說一句,二維字符串數組在C++中更容易,因爲'std :: vector '所以C++對你來說可能更容易。 – 2012-03-12 12:33:58

+0

看來C++已經結束了,看起來是這樣的 – DreamIt 2012-03-12 19:29:15

相關問題