Unborn Unborn - 1 year ago 78
C Question

how to get certain length string into 2d array in c

I'm trying to make a function that takes a string (ex: "Hello I am on stackoverflow") and print out said string with a given width. So if width was say 10

Hello I am

on stackov


`void Left(char* words, int width)
int length = strlen(words);
int divisions = length / width; //How many lines there will be
if (divisions%length!=0) divisions+=1; //If some spillover
printf("%d = divisions \n", divisions);
char output[divisions][width];
int i;
int temp;
for(i=0; i < divisions; i++)
strncpy(output[i][temp], words, width);
output[i][width] = '\0';
temp+= width;

This is the function I've writte so far. So output will have as many rows as there are new lines with each row having as much text as given by the width. I think I'm using strncpy wrong but I'm not sure. Any help?

Answer Source

You are going in right direction however some things needs to be recognized first:

char output[divisions][width];

is an array of strings which contains 'divisions' number of char strings each of size 'width'. And the strncpy takes 'char *' as an argument for destination buffer. http://man7.org/linux/man-pages/man3/strcpy.3.html

Hence to copy the data in your case, you need to provide the destination string as below-

strncpy(&output[i], words, width);

This will copy the 'width' length of data from string 'words' to string 'output[i]'.

Now for your function to work, you have to move the 'words' pointer forward after each iteration. For example: The first 10 bytes- "Hello I am" are copied from 'words' to 'output[0]' so you need to start coping from 11th byte in next iteration, so just add

words += width;
printf("%s \n", output[i]); 

Also, as mentioned in previous answer don't forget the string terminators and other boundary conditions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download