歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言 復制字符串 malloc

C語言 復制字符串 malloc

日期:2017/3/1 9:16:37   编辑:Linux編程
今天在看前輩的代碼,對其中字符串復制有時候直接把指針賦給另一個指針,有的malloc一個內存,然後把整個字符串的值拷貝過來,有點費解,就研究了一下,會了之後發現也沒什麼奧秘,其實很簡單,不過還是記錄一下比較好。 先寫結論:如果要拷貝的源字符串的內存會被回收,那麼就必須malloc一個內存再拷貝整個字符串(有時候malloc是防止修改源字符串,不過不考慮這個因素),如果不會被回收則不用。 下面是測試代碼

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

typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);

char *test_name = NULL;
int main(void)
{
  test(call_back);

  printf("name:%s\n", test_name);

  return 0;
}

void test(str_cpy_slk cb)
{
  char myname[8] = {0};
  snprintf(myname, sizeof(myname), "%s", "slk");
  printf("myname:%s\n", myname);
  cb(myname);
}

void call_back(char *name)
{
  test_name = name;
  printf("test_name:%s\n", test_name);
}

已不可顯示。 用malloc開辟內存,再賦值的話,則可以

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

typedef void(*str_cpy_slk)(char *name);
void test(str_cpy_slk cb);
void call_back(char *name);

char *test_name = NULL;
int main(void)
{
  test(call_back);

  printf("name:%s\n", test_name);

  free(test_name);

  return 0;
}

void test(str_cpy_slk cb)
{
  char myname[8] = {0};
  snprintf(myname, sizeof(myname), "%s", "slk");
  printf("myname:%s\n", myname);
  cb(myname);
}

void call_back(char *name)
{
  test_name = (char *)malloc(strlen(name) + 1);
  snprintf(test_name, strlen(name) + 1, "%s", name);
  printf("test_name:%s\n", test_name);
}

Copyright © Linux教程網 All Rights Reserved