0

I have a char array with the size of 128. I want to copy the first 32 to another char array. This is how i'm trying to do it:

char ticket[128];
data.readBytes(ticketLength, (BYTE*)ticket);
char sessionID[32];
strcpy(sessionID, ticket);

int userID = bdAuthService::checkLogin(sessionID);

The contents of "ticket" are "11aa14462ac96a9b389686672b99fa9e1IvtooKO6eVxVHO6URIQld8jFaceTaker" and when i'm trying to pass the sessionID to the checkLogin function it gets the same contents as ticket "11aa14462ac96a9b389686672b99fa9e1IvtooKO6eVxVHO6URIQld8jFaceTaker".

Can anyone help me here?

2
  • Looks like a bad mixture of zero terminated and non zero terminated strings Commented Nov 4, 2015 at 18:42
  • You better decide first whether to program in C or C++. Commented Nov 4, 2015 at 18:43

2 Answers 2

4

Use memcpy function instead.

memcpy( sessionID, ticket, sizeof( sessionID )  );

Take into account that sessionID won;t contain a string. It will contain "raw" characters.

As for function strcpy then it is designed to copy strings that is a sequence of characters termintaed by zero. So in case of your code fragment it will copy as many characters as there are characters in ticket before the character with value '\0' provided that such a character is present in ticket .

Sign up to request clarification or add additional context in comments.

7 Comments

When i use memcpy like you said the sid inside the called functions gets the value "593378e02614ebf8468cb67ca319bedaðúÙ,ûÙ@ wÞUVSþÿÿÿ„úÙ<" So it gets the bytes i want but adding useless stuff..
@BillAdonopoulos: because it is not null terminated
@BillAdonopoulos What is useless stuff? You said that you need to copy 32 characters. So where are the useless stuff from?
So how can i make it null terminated? If i set sessionID[33] i get null terminated string but it gets 33 characters not 32 that i need and with [32] it's not null terminated
@BillAdonopoulos I think that the problem is not with this copy operation. The problem is how ypu are using the result string further in your code.
|
0

You can use strncpy which allows you to specify the number of bytes to copy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.