Click here to Skip to main content
16,017,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, I'm trying in this code to cutting parts from char array and put it in another one in side struct, but I have error in output

the output :
lara200lara300h�y��
lara300lara400
lara400

it must be
lara200
lara300
lara400


What I have tried:

  #include <stdio.h>
  #include <stdlib.h>
  #include<string.h>
  #define InfoSize  3
  int main(int argc, char *argv[])
  {

  struct st
  {
     char name[50];
  };

 char nn[100]="lara100lara200lara300lara400" ;
 int start=7;  //represent the beginning of string
 int end=7;    // represent the length of string
 struct st info[InfoSize] = {0};


 for( int i = 0; i < InfoSize; ++i )
 {

            strncpy( info[i].name, &nn[start],end);
            printf("   %s \n", info[i].name);

    start+=7;


  }

}
Posted
Updated 24-Dec-17 11:43am
v7

1 solution

You need to append a null to the end of each substring you are copying. You can accomplish the same thing by initializing the structure to zero. Something like:
C++
struct st info[3] = { 0 };

Also - you need to have your for loop range from 0 to 2 because those are the indexes you need to access this array. The first item is 0 in C. The best way to think about it as an offset - the zero offset value is the first one.

One tip: having a size value or practically any other constant used literally is a bad idea that is prone to cause errors. In your program, there are three items in the structure and you loop through each of them in the for statement. What happens if you decide to have five elements? You have to find each place where you used three and change it. This is where errors can happen because with a larger program you are likely to miss one. It is better to have a single definition that everything else uses :
C++
#define InfoSize  3

struct st info[InfoSize] = {0};

for( int i = 0; i < InfoSize; ++i )
{
// logic goes here
}

This way, if you need five or eight or twenty items you change only one thing.
 
Share this answer
 
Comments
Lilyanaa 24-Dec-17 17:44pm    
I solve it :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900