-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;
4

4 回答 4

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>

于 2014-05-04T05:20:28.697 回答
3

第 13 行的错误最容易理解:names[3]是一个数组char;你不能只为它分配一个指针。在第 12 行,编译器正在转换names[3]为指针并尝试将其分配给数组names[2],这同样是做不到的。

尝试复制字符串。在 C 中,不能使用=操作符复制数组;使用来自memcpystrcpy家庭的功能。

于 2014-05-04T05:21:59.827 回答
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]);
}
于 2014-05-04T05:48:22.670 回答
0

names数组是一个二维字符数组。正如其他答案所指出的,当您想要复制一个字符数组时,您需要使用memcpyor strcpy

另一种解决方案是制作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]);
}

这种方法的优点是它允许您以您想要的方式操作指针。缺点是字符串是只读的。尝试修改字符串将导致未定义的行为。

于 2014-05-04T05:50:35.667 回答