2014-05-04 96 views
-1
main() { 
     char names [5][20] = { 
       "rmaesh", 
       "ram", 
       "suresh", 
       "sam" 
       "ramu" 
     }; 
char *t; 
     t = names[2]; 
     names[2] = names[3]; 
     names[3] = t; 

     printf(" the array elemsnt are \n"); 
     int i = 0; 
     for (i = 0; i < 5; i ++) 
       printf("\n%s", names[i]); 
} 

我收到以下錯誤,而編譯這個程序什麼是該類別中的代碼

stringarrary.c: In function ‘main’: 
stringarrary.c:12:11: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’ 
    names[2] = names[3]; 
     ^
stringarrary.c:13:11: error: incompatible types when assigning to type ‘char[20]’ from type ‘char *’ 
    names[3] = t; 

回答

3

是非法的嘗試並分配到一個數組的錯誤。在這種情況下,您應該使用strcpy函數。請注意,如果您打算交換兩個數組,則您的char *t;想法不起作用,因爲它只指向您現有的一個字符串;一旦你寫上names[2],那數據就沒有了。

char t[20]; 
strcpy(t, names[2]); 
strcpy(names[2], names[3]); 
strcpy(names[3], t); 

此外,"\n%s"應該是"%s\n" - 你想換行來你打印的內容之後。別忘了#include <stdio.h>#include <string.h>

3

第13行的錯誤最容易理解:names[3]是一個數組char;你不能只爲它指定一個指針。在第12行,編譯器正在將names[3]轉換爲一個指針,並試圖將其分配給數組names[2],這也是不能做到的。

請嘗試複製字符串。在C中,不能使用=運算符複製數組;使用memcpystrcpy家族的功能。

0

嘗試此

#include<stdio.h> 
#include <string.h> 
main() { 
    char names [5][20] = { 
     "rmaesh", 
     "ram", 
     "suresh", 
     "sam", //<----- You are missing this (,) at the end 
     "ramu" 
    }; 
char *t; 
    strcpy(t, names[2]); // And also use this syntax 
    strcpy(names[2] , names[3]); 
    strcpy(names[3], t); 

    printf(" the array elemsnt are \n"); 
    int i = 0; 
    for (i = 0; i < 5; i ++) 
     printf("\n%s", names[i]); 
} 
+0

您尚未向t分配任何內存。你應該在最後使用'char t [20]'或'char * t = malloc(20)'和'free(t)'。你的代碼會導致分段錯誤。 –

+0

此外'conio.h'不是標準文件(也不是clrscr) –

+0

@ Mohit Jain但是''C編譯器'中不能使用'char * t = malloc(20)'語法。你可以使用'char * t =(char *)malloc(20)':D –

0

names陣列是字符的二維陣列。正如其他答案指出的那樣,當您要複製一組字符時,您需要使用memcpystrcpy

替代解決方案是使names爲指針的一維數組。結果代碼看起來像這樣。

int main(void) 
{ 
    char *names[5] = { 
     "rmaesh", 
     "ram", 
     "suresh", 
     "sam", 
     "ramu" 
    }; 
    char *t; 

    t = names[2]; 
    names[2] = names[3]; 
    names[3] = t; 

    printf(" the array elemsnt are \n"); 
    int i = 0; 
    for (i = 0; i < 5; i ++) 
     printf("\n%s", names[i]); 
} 

這種方法的優點是它允許你按照你想要的方式操縱指針。缺點是字符串是隻讀的。嘗試修改字符串將導致未定義的行爲。

相關問題