c - 获取 char* 的正确地址

标签 c pointers

我试图理解 C 中 char* 操作的行为。 这是我的驱动程序代码:

char *str1 = malloc(30);
char *str2 = "hello programmers.";
char *str4 = "and have a nice day.";
char *str5 = my_strcat(str2, str4);
my_strcpy(str1, str2);

以及我对 strcpy 的实现:

void my_strcpy(char *dest, char *src){
  while ((*dest++ = *src++)); //dest value is at end of char*
}

1.当离开 my_strcpy 时,据我所知,dest 应该指向字符串的末尾(因为我们一直在递增它)。

现在让我们看看我的 strcat:

char* my_strcat(char *first, char *second){
  int l_first = strlen(first), l_second = strlen(second);
  char *tmp = malloc (l_first + l_second + 1);

  while ((*tmp++ = *first++));
  tmp--; // overwrite tmp's "\0"
  while ((*tmp++ = *second++)); // tmp value is end of char*
  tmp-=(l_first+l_second + 1); // rewinding pointer to string start.
  return tmp;
}

2。我不得不手动“倒带” tmp 以使其在函数外正确打印。

我的问题,简而言之,我为什么会出现这种行为?我不太确定如何描述我的问题,我希望它足够清楚。为什么我必须在第二个函数中“倒回”我的指针,而不是第一个?此外,为什么我不必在第一个函数中“倒回”srcdest

我想到的可能的解释:

  1. char* 按值传递给函数,这就是为什么我不必倒带 srcdest - 被调试器证明是错误的(检查地址进出功能范围)。
  2. 在第一个函数中,我将分配在范围外的指针作为 dest 传递,而在第二个函数中,tmp 是在范围内分配的。

谢谢 (我试图提供尽可能多的信息和尝试的解决方案,就像一个很好的 SO 问题应该是,如果它出来太长,抱歉)

最佳答案

Why did I have to "rewind" my pointer in the second function, but not the first? Moreover, why didn't I had to "rewind" src and dest in the first function

这是因为在 C 中一切都是按值传递。

  1. 当我们按值传递时,我们将变量的副本传递给函数。

  2. 当我们通过引用传递时,我们将变量的别名传递给函数。 它正在将指针的值、地址复制到函数中。

因此,当您执行 (*dest++ = *src++) 时,您不会递增实际变量,因此您的 str2str4 不会受到影响.

char* my_strcat(char *first, char *second) 的情况下,您将返回指向连接字符串中最后一个字符的本地指针,因此您需要倒带。

如果您不想倒回指针,则只需使用一个指向 tmp 开头的虚拟指针,然后返回虚拟指针,如下所示。

char* my_strcat(char *first, char *second){
  int l_first = strlen(first), l_second = strlen(second);
  char *tmp = malloc (l_first + l_second + 1);

  char *result = temp;

  while ((*tmp++ = *first++));
  tmp--; // overwrite tmp's "\0"
  while ((*tmp++ = *second++)); // tmp value is end of char*

  return result;
}

关于c - 获取 char* 的正确地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389315/

相关文章:

无法 malloc 然后转到程序顶部

c - 如何为字符指针添加偏移量?

c++ - 为什么我不能将一个非 const 指针传递给一个以指向 const 的指针作为参数的函数

c - Memcpy 到 malloced 结构内的数组中

c 函数调用

c - 为什么 strtol() 对于非常大的数字返回 -1?

c - realloc 会覆盖旧内容吗?

c - 为什么连续数组条目的地址不是连续的?

java - 从对象数组中的 HashMap 对象创建指针

objective-c - 在 Objective-C 中在另一个自定义类中使用自定义类