c - 为什么这些词不附加在 C 中?

标签 c pointers

我正在尝试编写一个将两个单词附加到第三个字符串的函数,并且此函数必须使用 malloc()。在将它放入函数之前,我首先将它写在 main 中。我有:

int main(void){

    char *word = "Johnny";
    char *word2 = " Boy";
    char *buff = malloc(100 * sizeof(char));
    printf("%d\n", sizeof(buff));
    int ct;
    for(ct = 0; ct < strlen(word); ct++){
        buff = word;
    }
    printf("%s\n", buff);
    printf("the counter is now %d\n", ct);

    buff += ct;
    for(ct; ct < 13; ct++){
        buff = word2;
    }

   printf("%s\n", buff);    
}

我想让 buff 说“Johnny Boy”,但最后“Johnny”被覆盖了,它只说“Boy”

最佳答案

听着,虽然我们想提供帮助,但 SO 并不是真正意义上的类环境。很明显,您在根本上缺乏对 C 中指针/字符串操作的理解,这是非常基础的 Material 。获取一本关于 C 的更好的书,并将此代码与您的工作进行比较,并研究它,直到您了解差异以及每一步的具体操作。

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

int main(void){
  char word[] = "Johnny";
  char word2[] = " Boy";
  char *temp;
  char *buff = malloc(32 * sizeof(char));
  if (buff == NULL) {
    puts("allocation error");
    return 1;
  }
  for (int ct = 0; ct <= strlen(word); ct++) {
    buff[ct] = word[ct];
  }
  printf("%s\n", buff);
  temp = buff + strlen(word);
  for (int ct = 0; ct <= strlen(word2); ct++) {
    temp[ct] = word2[ct];
  }
  printf("%s\n", buff);
  free(buff);
  return 0;
}

关于c - 为什么这些词不附加在 C 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45135038/

相关文章:

将负十进制转换为二进制

c - 帧速率随窗口大小变化

c - 为什么restrict指针没有作用

ios - 为什么 CGImage 的 copy() 方法会在相同的内存地址上生成图像?

iphone - 什么时候写“NSString * str”或“NSString str”?

c - 多客户端聊天程序: send messages to all Clients

c - WIFSIGNALED、WIFSTOPPED、WIFCONTINUED 的 C 语言测试用例

php - 为什么openssl无法解码php的base64_encode函数编码的字符串?

c# - C++/CLI 双指针类型转换为 ref IntPtr 以进行 C# 访问

c++ - 数组是否被称为隐式指针