朋乌龟 发表于 2019-10-15 17:59:33

有关strcpy函数的问题

#include <string.h>
#include <stdio.h>
void main()
{
   int i,j,c;
   char p;
   char *arr1={"123","321","213"};
   char **arr=arr1;   
   for(i=0;i<2;i++)
   {
          for(j=0;j<2-i;j++)
          {
            if((c=strcmp( *(arr+j),*(arr+j+1) )) <0)
            {
                  strcpy(p,*(arr+j));   /*这里能复制过去
                  strcpy(*(arr+j),*(arr+j+1));/*这里为什么不行
                  strcpy(*(arr+j+1),p);

            }
          }
   }
   printf("%s %s %s",*(arr+0),*(arr+1),*(arr+2));
   
}

xypmyp 发表于 2019-10-16 10:59:58

本帖最后由 xypmyp 于 2019-10-16 11:08 编辑

The problem related to how pointer works in 2D array.

/*
        int i, j, c;
        char arr = {
                {"123"},
                {"321"},
                {"213"}
        };

        char* pointerTo2DArray = &arr;
*/

        int i, j, c;
        char p;
        char *arr1 = { "123","321","213" };
        char **arr = arr1;
       
        strcpy((char*)((int*)arr +0), (char*)((int*)arr + 1));

        printf("%s %s %s", (char*)*((int*)arr + 0), (char*)*((int*)arr + 1),(char*)*((int*)arr + 2));
        getchar();
        return 0;


As the lever 1 address is pointing to a memory address which 4 Byte long = sizeof(int), than you convert it to (char*) which strcpy() required .

朋乌龟 发表于 2019-10-16 22:34:30

xypmyp 发表于 2019-10-16 10:59
The problem related to how pointer works in 2D array.




虽然看不大懂,但还是要谢谢你

xypmyp 发表于 2019-10-17 10:46:42

朋乌龟 发表于 2019-10-16 22:34
虽然看不大懂,但还是要谢谢你

Which part you don't understand?

朋乌龟 发表于 2019-10-17 16:23:37

xypmyp 发表于 2019-10-17 10:46
Which part you don't understand?

我可以交换首地址来交换位置,不需要strcpy(),
我理解的是:*(arr+0)这是整形指针?需要把它转换成字符型??

xypmyp 发表于 2019-10-17 21:02:52

Yes, as arr is a type of (char**), you have to convert it to (char*)

*(arr+0) is not a (int*) pointer, it's a (char**) pointer which you declare at the beginning,
so you have to convert it to (int*) for pointing to an valid address. which is the start address of the string.
then, you have to convert it to (char*), as the function strcpy() needs a (char*) pointer.

Try +1 or -1 in between, you may understand what i'm saying
printf("%s",((char*)*((int*)arr + 0) +1));

朋乌龟 发表于 2019-10-18 11:17:06

为什么我一定要将其转换为(int *)才能指向有效地址
我这样也可以,对吗?int i, j, c;
      char p;
      char *arr1 = { "123","321","213" };
      char **arr = arr1;
      
      strcpy((arr +0), (arr + 1));

      printf("%s %s %s", *(arr + 0), *(arr + 1),*(arr + 2));
      getchar();
页: [1]
查看完整版本: 有关strcpy函数的问题