简体   繁体   English

无法通过strcpy从参数复制到char数组中

[英]Can not copy into char array from argument via strcpy

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

void doSth(char *a)
{
    char *b,*c;
    b = malloc(2*sizeof(char));
    b[0]='a';
    b[1]='\0';

    a = malloc(2*sizeof(char));
    c = malloc(2*sizeof(char));
    strcpy(a,b);
    strcpy(c,b);

    printf("c:%s\n",c);
    free(c);
    free(b);
}


int main()
{
    char *myString;

    doSth(myString);

    printf("%s\n",myString);

    free(myString);
    return 0;
}

This program outputs only "c:a". 该程序仅输出“ c:a”。 Why can't I copy b to a? 为什么我不能将b复制到a? According to the debugger, the variable "a" remains empty in every line. 根据调试器,变量“ a”在每一行中都为空。

By doing a = malloc(2*sizeof(char)); 通过执行a = malloc(2*sizeof(char)); in function void doSth(char *a) , a local copy of a is modified in the scope of the function, but not out of it. 在功能void doSth(char *a) ,的本地副本a在功能范围修改,但不出来。 If you wish to modify myString , a pointer to myString ( &myString ) should be given to the function. 如果要修改myString ,则应将指向myString&myString )的指针赋予该函数。 It is called passing by pointer : 称为通过指针传递:

char *myString;

doSth(&myString);

The prototype of the function is changed accordingly : 该函数的原型相应地进行了更改:

void doSth(char **a){
  ...
  *a = malloc(2*sizeof(char));
  strcpy(*a,b);
  ...
}

For the same reason, it is int a=1;printf("%d",a); 出于相同的原因,它是int a=1;printf("%d",a); ( printf just needs the value of a ), but int a;scanf("%d",&a); printf只是需要的值a ),但int a;scanf("%d",&a); ( scanf needs a pointer to a , to modify the value of a in the main). scanf需要一个指向a ,要修改的值a在主)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM