如何在另一个指针的内部给出一个参数? [英] How to give a parameter the inside of another pointer?

查看:64
本文介绍了如何在另一个指针的内部给出一个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将结构中的名称保存在与我作为参数收到的原始副本不同的副本中,我这样做但是由于免费的东西它是错误的...但我必须在此内部自由功能我猜..当我尝试在eclipde中运行我的程序时它只是告诉我我有什么不对,当我运行debbug时会发生同样的事情...我知道问题是免费的,因为如果我删除免费一切都很完美!



我尝试过:



i want to save name in the struct something in a different copy than the original copy that i recieved as a parameter , i did this but it is wrong because of the free thing .. but i have to do free inside of this function i guess .. when i try to run my program in eclipde it just tells me i have something wrong and the same thing happens when i tru to run the debbug .. i know for sure the problem is with free because if i deleate free everything works perfectly !

What I have tried:

<pre>typedef struct Ssomething {
  int num;
  char *name;
  Level level;
} Something;







Result copy_name(Something *something, char *name) {
  if (something == NULL || name == NULL) {
    return NULL_PARAMETER;
  }
  char *name2 = malloc(strlen(name) + 1);
  if (name2 == NULL) {
    return MEMORY_PROBLEM;
  }
  memcpy(name2, name, strlen(name) + 1);
  something->name = name2;
  free(name2);
  return OK;
}

推荐答案

char *name2 = malloc(strlen(name) + 1); // allocate new buffer for name2
// ...
memcpy(name2, name, strlen(name) + 1); // copy name to newly allocated buffer
something->name = name2;               // save the pointer in the struct
free(name2);                           // free the buffer just allocated



所以你创建 name2 然后立即扔掉它。难怪程序失败。


So you create name2 and then immediately throw it away. No wonder the program fails.


这篇关于如何在另一个指针的内部给出一个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆