简体   繁体   中英

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

erflow

`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?

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.

The width of the string does not include the string terminator, therefore output[i][width] = '\\0'; will write the terminator out of bounds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM