将字符串指定给字符串

时间:2016-10-27 13:55:55

标签: c arrays pointers 2d

我尝试在网上搜索,但发现没有像我想做的那样。希望你能帮助我。

问题:我有2个char数组,即For Each ws1 In Worksheets If ws1.Name <> "Sheet1" And ws1.Name <> "Extra" Then **ws1.Range("A1:V1000").Select** Something is wrong here I suspect ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Clear ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("I2:I1000") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal ActiveWorkbook.Worksheets(ws1).Sort.SortFields.Add Key:=Range("T2:T1000") _ , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal With ActiveWorkbook.Worksheets(ws1).Sort .SetRange Range("A1:V1000") .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply End With End If Next ws1 string。两者最初都是空的。然后我给这些字符串输入2个输入。我想使用指向string2的指针在字符串中赋值。

这是我的代码:

string2

*编辑 我知道我可以使用strcpy,但我试图学习使用指针。在这方面的任何帮助都会很棒。

1 个答案:

答案 0 :(得分:0)

因为您没有复制编译器可以理解的整个信息结构,所以您需要单独复制数组的每个元素。通常这是通过for循环检查NUL或大小来完成的,但我作弊并且只是向您显示可以执行所需副本的语法:

#define MAXLEN 10

int main(void) 
{
    char string[2][MAXLEN];
    char string2[2][MAXLEN];
    char *pointer[2];
    pointer[0] = &string2[0];
    pointer[1] = &string2[1];

    // Replace scanf for simplicity
    string[0][0] = 'a'; string[0][1] = 'b'; string[0][2] = '\0';
    string[1][0] = 'c'; string[1][1] = 'b'; string[1][2] = '\0';

    // For loop or strcpy/strncpy/etc. are better, but showing array method of copying
    pointer[0][0] = string[1][0];
    pointer[0][1] = string[1][1];
    pointer[0][2] = string[1][2];

    printf("%s", string2[0]);

    return 0;
}

对于指针,你可以这样做:

#define MAXLEN 10

int main(void) {
  char string[2][MAXLEN];
  char string2[2][MAXLEN];
  char *pointer[2];
  pointer[0] = &string2[0];
  pointer[1] = &string[1];  // changed this

  string[0][0] = 'a'; string[0][1] = 'b'; string[0][2] = '\0';
  string[1][0] = 'c'; string[1][1] = 'd'; string[1][2] = '\0';

  *pointer[0]++ = *pointer[1]++;
  *pointer[0]++ = *pointer[1]++;
  *pointer[0]++ = *pointer[1]++;

  printf("%s", string2[0]);

  return 0;
}

上面的指针魔术变成:

  char temp = *pointer[1];  // Read the char from dest.
  pointer[1]++;  // Increment the source pointer to the next char.
  *pointer[0] = temp;  // Store the read char.
  pointer[0]++;   // Increment the dest pointer to the next location.

我做了3次 - 每个输入字符一个。使用while()检查sourcePtr ==&#39; \ 0&#39;基本上把它变成strcpy()。

另一个有趣的示例,其中取消引用可能会达到您的期望:

typedef struct foo
{
    char mystring[16];
} FOO;

FOO a,b;

// This does a copy
a = b;

// This also does a copy
FOO *p1 = &a, *p2=&b;
*p1 = *p2;

// As does this
*p1 = a;

// But this does not and will not compile:
a.mystring = b.mystring;

// Because arrays in 'C' are treated different than other types.
// The above says: Take the address of b.mystring and assign it (illegally because the array's location in memory cannot be changed like this) to a.mystring.