c - 反向存储值(value)?

标签 c pointers

我编写了使用指针连接两个字符串的函数。和strcat(s,t)一样,所以在s的末尾会加上t..

   int main ()
{
  char b[] = "Hello";
  char b1[] = "world";
  string_cat(b,b1);
  printf("Concatenated string is %s\n",b);
  return 0;
}
int string_cat(char *s, char *d)
{
  while(*++s != '\0')
    ;
  *s++ = ' ';
  while((*s++ = *d++)!='\0');  // Concatenation
  printf("S is %c\n",s[-2]);   // Just to see the values
}

串联工作正常,但是当我想查看元素的存储方式时,所有元素都存储在负方向,我的意思是 s[-2] 等于 'd',s[-3] 等于 ' l' .. 这是它们的存储方式吗?

最佳答案

首先 b 太小,无法容纳连接的字符串。它只有足够的空间来容纳 Hello\0 所以你在做什么是未定义的。其次,看这一行:

while((*s++ = *d++)!='\0');
        ^^^

你在推进 s 因为你在递增它。每次增加它时,您都应该想象它指向一个元素。当你走到尽头时,s 并不是它开始时的样子。所以 s[-2] 实际上比原来的 s 更靠后(在你的例子中是 b)。


编辑

so, how to declare it, so that it dynamically adjusts to new size?

如果可能的话,很难将其调整到合适的大小。你可以做什么:

  • 这样声明:char b[LENGTH] = "Hello";
  • 将另一个参数传递给 string_cat 指定大小

经过多次迭代后,您最终会得到类似 strncpy/memcpy 的东西。

关于c - 反向存储值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14191588/

相关文章:

c - 为矩阵和用户输入动态分配内存

c - 为什么 scanf 对大 float 输入错误?

c++ - 删除 BST 中有两个 child 的节点

我可以在循环中定义一个数组,其大小在每次迭代中都不同吗

pointers - Fortran 指针算术

c - 'strcpy' 与 'malloc' ?

c - strcpy 复制到其他字符数组

objective-c - 当 float 不为零时,则将其视为零

c++ - 你在 C++ 的析构函数中调用 delete 吗?

c - 通过强制转换取消引用 void 指针