JupiterOrange
JupiterOrange

Reputation: 349

Assign value to element of dynamic array

I have two arrays:

char line[128] which is populated using:

fgets(line,sizeof line, file)

and

char* array;
  array=(char*) malloc(j*sizeof(char));

where j is some integer.

I'd like to assign an element of "line" to the corresponding element of "array".

Thanks in advance for any help!

Upvotes: 1

Views: 2424

Answers (2)

mathematician1975
mathematician1975

Reputation: 21351

As these are char arrays you could just use strcpy

 strcpy(array,line);

taking care that your dynamic array is large enough to accomodate the line array. This would copy the whole array, or for just an individual element,

 array[i] = line[i];

taking care that i is within limits of the arrays.

Upvotes: 1

Mahesh
Mahesh

Reputation: 34625

 array[N] = line[N]; // N is the corresponding element's index

But you have to make sure that N is a valid index w.r.t both array and line.

Upvotes: 0

Related Questions