Copying part of an array into another variable

17k views Asked by At

So I'm trying to copy part of an array into another array in the simplest way possible. I was trying to avoid using a loop. This was my thought process...

char date[]="20140805";
char year =date[0..3];

The ".." is what is causing the error. I want to be able to break up the date variable into parts, and was hoping to be able to do so compactly in one line like this. Some help would be appreciated.

3

There are 3 answers

6
Iharob Al Asimi On BEST ANSWER

You should not use a loop.

char year[5];
char date[] = "20140805";

memcpy(year, date, 4);
year[4] = 0;

that's how you should do it, or may be you want

char date[] = "20140805";
char year[] = {date[0], date[1], date[2], date[3], 0};
2
Ali Akber On

Here is an example to do that :

In fact you can copy any part of a string using this method :)

just change the from and sz variable and you are done :)

#include <stdio.h>
#include <string.h>
int main ()
{
  char date[]= "20140805";
  int sz=4; // number of characters to copy

  char year[sz+1];
  int from = 0; // here from is where you start to copy

  strncpy ( year, date + from, sz );

  year[sz]=0;

  puts (year);

  return 0;
}
1
Weather Vane On

OP wanted a one-liner: here in one declaration plus one line.

char year[5] = {0};
strncpy(year,date,4);

This answer addresses the weak point of strncpy() which does not append a final 0 if count <= strlen(source);. It's not the best solution but it answers OP's question while avoiding the trap.

Byte dumps of the char array before and after the strncpy()

0 0 0 0 0
50 48 49 52 0