如何使用strcpy指针?

时间:2016-03-28 01:24:27

标签: c string pointers

为什么它停止工作?我们不能将指针的名称作为strcpy的参数传递吗?如果我将其更改为strcpy(&a,&b);则可行。

#include <stdio.h>

    int main() {

    char *a;
    a = "aabtyn";

    char *b;
    b =  "mihli";

    strcpy(a,b);

    printf("%s-%s\n",a,b);


    return 0;
}

3 个答案:

答案 0 :(得分:1)

  

我们不能将指针的名称作为strcpy的参数传递吗?

是的,我们可以。但是,目标指针指向可写存储器也很重要;在您的情况下,ab都没有指向可以写入的内存。

  

如果我将其更改为strcpy(&a,&b);则可以。

如果它似乎适用于您的系统,则会错误地执行此操作。你看到的是未定义的行为。要使strcpy正常工作,您需要执行以下操作之一:

  • 通过将a定义为char a[] = "aabtyn";
  • ,将a分配到自动记忆中
  • 通过调用char *a = malloc(7);在动态内存中分配Sub test() SplitEveryThird_2 Range("A1:O1") End Sub Sub SplitEveryThird_2(rng As Range) 'where: 'rng is only the 1 rows of the columns with the data 'the address of rng would be A1:O1 in my case Dim x As Integer Dim r 'to store the last row of the column Dim theCol As Range For x = 1 To rng.Count If (x Mod 3) = 1 Then r = Range(Cells(1, x), Cells(1, x)).End(xlDown).Row 'this is to take the last row of the column 'you could use this: 'r = range(cells(1048576,x),cells(1048576,x)).End(xlUp).Row 'gives you the same result, with the difference that if the range 'with the data has empty rows, would be no problem Set theCol = Range(Cells(1, x), Cells(r, x)) 'Split column at the comma 'here you say to put the result in the first row of the 'selected column, not just in A1 theCol.TextToColumns _ Destination:=Range(Cells(1, x), Cells(1, x)), _ DataType:=xlDelimited, _ Tab:=False, _ Semicolon:=False, _ Comma:=True, _ Space:=False, _ Other:=False, _ OtherChar:="-" End If Set theCol = Nothing Next x End Sub 。您需要第七个字节用于空终止符。

答案 1 :(得分:0)

如果你有:

char source[80],dest[80];

初始化源,然后:

strcpy(dest,source);

但如果你有:

char *pd,*ps;

初始化 * pd 的源和malloc存储,然后:

strcpy(&pd,&ps);

请记住在退出(0)之前的某处 free(pd); ;

答案 2 :(得分:0)

根据C标准(6.4.5字符串文字)

  

7未指明这些阵列是否与它们不同   元素具有适当的值。 如果程序尝试   修改这样的数组,行为是未定义的。

你声明了两个指向字符串文字的指针

char *a;
a = "aabtyn";

char *b;
b =  "mihli";

然后在本声明中

strcpy(a,b);

您正在尝试修改第一个字符串文字。所以程序的行为是不确定的。

至于这句话

strcpy(&a,&b); 

然后尝试将一个指针的值复制到另一个指针。此调用aslo具有未定义的行为。但是如果第二个指针的值为零终止,则此调用可以等效于

a = b;

所以第一个指针刚刚重新分配。虽然在任何情况下都存在未定义的行为。

有效程序可以按以下方式查看

#include <stdio.h>
#include <string.h>

int main( void ) 
{
    char s[] = "aabtyn";

    char *a = s;

    char *b;
    b =  "mihli";

    strcpy(a,b);

    printf("%s-%s\n",a,b);

    return 0;
}