【问题标题】:How to copy a string using a pointer如何使用指针复制字符串
【发布时间】:2013-09-27 03:23:01
【问题描述】:

这是我编写的用于复制字符串常量的程序。

程序运行时崩溃。为什么会这样?

#include <stdio.h>

char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char c;
char *l;

main(){
   while((c = *alpha++)!='\0')
       *l++ = *alpha;
   printf("%s\n",l);
}

【问题讨论】:

  • 您需要为“l”分配空间。例如:char *l = malloc(strlen(alpha)+1);。 PS:一定要熟悉调试器。它会向您准确显示崩溃的位置……这对于理解原因和解决问题很重要。恕我直言...

标签: c string pointers


【解决方案1】:

要在 C 中复制字符串,可以使用 strcpy。这是一个例子:

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

const char * my_str = "Content";
char * my_copy;
my_copy = malloc(sizeof(char) * (strlen(my_str) + 1));
strcpy(my_copy,my_str);

如果您想避免意外的缓冲区溢出,请使用strncpy 而不是strcpy。例如:

const char * my_str = "Content";
const size_t len_my_str = strlen(my_str) + 1;
char * my_copy = malloc(len_my_str);
strncpy(my_copy, my_str, len_my_str);

【讨论】:

  • "sizeof(char)" 是不必要的——大多数人会认为你应该把它排除在外。恕我直言......同样值得注意的是C有strdup(),它将malloc()和strcpy()结合在一起。但最重要的一点是分配空间给“*”指向。
  • malloc 的空格是尾随\0 的一个字节。
  • strdup 根本不是一个好的选择,因为它不是 C 标准函数。
  • @YuHao 这个问题终于解决了,只用了4年多一点。 :)
【解决方案2】:

要执行这样的手动复制

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

int main()
{
    char* orig_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char* ptr = orig_str;

    // Memory layout for orig_str:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // |A|B|C|D|E|F|G|H|I|J|K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z |\0|  --> data
    // ------------------------------------------------------------------------

    int orig_str_size = 0;
    char* bkup_copy = NULL;

    // Count the number of characters in the original string
    while (*ptr++ != '\0')
        orig_str_size++;        

    printf("Size of the original string: %d\n", orig_str_size);

    /* Dynamically allocate space for the backup copy */ 

    // Why orig_str_size plus 1? We add +1 to account for the mandatory 
    // '\0' at the end of the string.
    bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));

    // Place the '\0' character at the end of the backup string.
    bkup_copy[orig_str_size] = '\0'; 

    // Current memory layout for bkup_copy:
    // ------------------------------------------------------------------------
    // |0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|  --> indices
    // ------------------------------------------------------------------------
    // | | | | | | | | | | |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |\0|  --> data
    // ------------------------------------------------------------------------

    /* Finally, copy the characters from one string to the other */ 

    // Remember to reset the helper pointer so it points to the beginning 
    // of the original string!
    ptr = &orig_str[0]; 
    int idx = 0;
    while (*ptr != '\0')
        bkup_copy[idx++] = *ptr++;

    printf("Original String: %s\n", orig_str);   
    printf("Backup String: %s\n", bkup_copy);

    return 0;
}

【讨论】:

  • 你可能打算写bkup_copy = (char*) malloc((orig_str_size+1) * sizeof(char));(注意orig_str_size+1周围的括号)?
  • 我认为因为我们在讨论指针,这段代码可能更有意义:ptr = orig_str(逻辑上它与ptr = &amp;orig_str[0] 相同)但更优雅一点。这只是我的意见。
【解决方案3】:

您需要为l 分配空间。目前它指向内存中的一个随机点,如果您尝试写入该点,操作系统可能会关闭(AKA 崩溃)您的应用程序。如果您希望代码按原样工作,请为 lmalloc() 分配一些空间,或者将 l 创建为具有足够空间以容纳 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 和 NULL 终止符的字符数组。

请参阅 http://cslibrary.stanford.edu/106/ 了解指针入门。

【讨论】:

    【解决方案4】:

    复制一个字符串“常量/文字/指针”

    char *str = "some string thats not malloc'd";
    char *tmp = NULL; 
    int i = 0; 
    for (i = 0; i < 6; i++) {
        tmp = &str[i];
    }
    printf("%s\n", tmp);
    

    反转

    char *str = "some stupid string"; 
    char *tmp, *ptr = NULL; 
    ptr = str;
    while (*str) { ++str; } 
    int len = str - ptr;
    int i = 0;
    for (i = len; i > 11; i--) {
        tmp = &ptr[i];
    } 
    printf("%s\n", tmp); 
    

    tmp = &amp;blah[i] 可以与tmp = &amp;(*(blah + i)) 互换。

    【讨论】:

      【解决方案5】:
      #include <stdio.h>
      #include <string.h>
      #define MAX_LENGTH 256
      int main(void) {
          char *original, *copy, *start; //three character pointers
          original = malloc(sizeof(char) * MAX_LENGTH); //assigning memory for strings is good practice
          gets(original); //get original string from input
          copy = malloc(sizeof(char) * (strlen(original)+1)); //+1 for \0
      
          start = copy;
          while((*original)!='\0')
             *copy++ = *original++;
          *copy = '\0';
          copy = start;
      
          printf("The copy of input string is \"%s\".",copy);
          return 0;
      }
      

      【讨论】:

        【解决方案6】:

        你可以直接做下面的代码:

        char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char *l = alpha;
        

        如果您的代码如下:

        const char *alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const char *l = alpha;
        

        :)

        【讨论】:

          【解决方案7】:

          cpy函数会接受两个char指针,src指针指向main函数中定义的src(char数组)的起始字符,和des指针一样指向des(char数组)的起始位置在 main 函数中定义,并且 src 指针的 while 循环值会将值分配给 des 指针并将指针递增到下一个元素,这将发生直到 while 循环遇到 null 并退出循环并且 des 指针将简单取完所有值后赋值为null。

          #include<stdio.h>
          void cpy(char *src,char *des)
          {
               while(*(des++) = *(src++));
               *des = '\0';
          }
          
          int main()
          {
               char src[100];
               char des[100];
               gets(src);
               cpy(src,des);
               printf("%s",des);
          }
          

          输出:Image

          【讨论】:

          • 请添加一些解释如何解决所提出的问题。仅发布代码意味着您的答案质量低且价值低。
          猜你喜欢
          • 1970-01-01
          • 2010-09-27
          • 2015-01-17
          • 2011-11-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多