通过在c中递增数组来复制字符串

时间:2014-04-12 16:25:42

标签: c arrays

我正在尝试搜索数组中的特定元素并复制到其他元素。

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

void main() 
{ 
   unsigned char a[16] = "1011\n23578A23\n\r"; 
   unsigned char b[9]; 
   unsigned char c[5]; 
   unsigned char d[5] = "1011"; 
   int i = 4; 

   memcpy(c,a,4); 
  printf("%s\n", c); 
  if(strcmp(c,d) == 0) 
  { 
    printf("\nEnter\n"); 
        while(a[i] != '\r') 
        { 
          if(a[i] == '\n') 
          { 
              i = i+1; 
                printf("start copying\n"); 
                memcpy(b,&a[i],8); 
          } 
          i = i+8; 
       }
    }
}

但我得到了段错误。我对增量的看法是错误的吗?

2 个答案:

答案 0 :(得分:0)

您必须在c字符串中设置空终止符。

  memcpy(c,a,3); 
  c[4] = 0;
  printf("%s\n", c); 

答案 1 :(得分:0)

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

int main(){
    unsigned char a[16] = "1011\n23578A23\n\r";
    unsigned char b[9] = {0};
    unsigned char c[5] = {0};
    unsigned char d[5] = "1011";
    int i = 4;

    memcpy(c,a,4);
    printf("%s\n", c); 
    if(strcmp(c,d) == 0){
        printf("\nEnter\n");
        if(a[i] == '\n'){
            i = i + 1;
            printf("start copying\n");
            memcpy(b, &a[i],8);
            //printf("%s\n", b); 
            //i = i + 8; 
       }
    }
}