• C

extract data from char array

Hi All,

can some one give me some sample code for parsing character to return for example middle 5 characters from a buffer or the last 2.

What i tried initially was to cast a character array to a structure with all character arrays as the fields in the struct. (because i know the format of the char array). Why doesn't this work?

char array[10] = "1234567890"

typedef struct {
  char field1[2];
  char field2[5];
  char field3[3];
}s_test;

char *ptr = array;

s_test *data = (s_test *)ptr;

data->field1 should equal "12"?
data->field2 should equal "34567"?
data->field3 should equal "890"?

Thanks




LVL 2
pesstAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sunnycoderCommented:
>can some one give me some sample code for parsing character to return for example middle 5 characters
>from a buffer or the last 2.

char buffer[200];
char result[10];

/*buffer holds your string and result is where you want chars 15-20 */

strncpy ( result, buffer+15, 5 );
buffer[6] = '\0';

>s_test *data = (s_test *)ptr;
compiler will not allow the cast between char * and a struct ... use memcpy

char array[10] = "1234567890"

typedef struct {
 char field1[2];
 char field2[5];
 char field3[3];
}s_test;

struct s_test test;
memcpy ( test, array, 10 );

make sure that you know the format and behaviour of the array throughout the program or you may end up pulling you hair our
also portability of such tricks is suspect due to issues like structure padding
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
migoEXCommented:
Note, that even in this case, where field[2] is "34567", you can't use it in str* functions, as next character is not '\0'. actually, this definition is equivalent to:

typedef struct {
   char buf[11];
   char* field1;
   char* field2;
   char* field3;
} s_test;

struct s_test test;
strcpy( test.buf, "1234567890" );
test.field1 = test.buf;
test.field2 = test.buf + 2;
test.field3 = test.field2 + 5;
0
itsmeandnobodyelseCommented:
> Why doesn't this work?

I tried your code and the only thing to change was

    char array[11] = "1234567890";

because a terminating zero character must be added to a quoted string constant;

The contents of data was correct, i. e.

       data->field1[0] = '1';
       data->field1[1] = '2';
       ...
       data->field3[2] = '0';

However, only data->field3 may be correctly used as a string by string functions because of the terminating zero.

Regards, Alex

       
0
Become a Leader in Data Analytics

Gain the power to turn raw data into better business decisions and outcomes in your industry. Transform your career future by earning your MS in Data Analytics. WGU’s MSDA program curriculum features IT certifications from Oracle and SAS.  

rstaveleyCommented:
data->field2 does indeed get you the address of the expected portion of string, but in the absence of '\0' termination, you need to supply printf additional information to let it know how many characters to print.
--------8<--------
#include <stdio.h>

char array[10] = "1234567890";
typedef struct {
  char field1[2];
  char field2[5];
  char field3[3];
} s_test;
s_test *data = (s_test*)array;

int main()
{
        printf("data->field1 should equal \"%.2s\"\n",data->field1);
        printf("data->field2 should equal \"%.5s\"\n",data->field2);
        printf("data->field3 should equal \"%.3s\"\n",data->field3);
}
--------8<--------
0
pesstAuthor Commented:
Thanks for all the information guys. I went ahead and just created a separate array for each field and used:

strncpy(field1,data, 2)
field1[2] = '\0'

strncpy(field1,data+2, 5)
field2[5] = '\0'

strncpy(field1,data+7, 3)
field3[3] = '\0'

So I'll give the points to the first answer.


0
rstaveleyCommented:
Also... Notice that you have set the sizeof(array) to 10. This means that array doesn't get a '\0' terminator. If you'd not explicitly set the size to 10, sizeof(array) would be 11 and a '\0' terminator would be added.

You'd be lucky to get away with doing a printf on the array without specifying its length in the format specifier, because of the lack of '\0' terminator.

The following illustration uses a byte-aligned struct to illustrate the point.
--------8<--------
#include <stdio.h>

/* Byte alignment - otherwise we'd get padding spoiling the illustration :-) */
#pragma pack(1)
struct X {
char array[10];
char secret[10];
};
#pragma pack()

struct X s = {
        "1234567890"      /* 10 characters - no space for '\0'! */
        ,"abcdefgh"      /* 8 characters - fits in with '\0' termination */
        };

int main()
{
        printf("The s.array pointer gets us \"%s\" (s.array's size is %u)\n",s.array,sizeof(s.array));
}
--------8<--------

By byte aligning the structure, I ensured that the compiler doesn't word align secret and put it on a word boundary leaving zero padding between array and secret. This would effectively give you '\0' termination. You should see the same effect without byte-alignment on a 32-bit system, if you made the array size 8 chars (or 4, 12, 16 etc.).

e.g. This should show the effect on most 32 or 16 bit systems:
--------8<--------
#include <stdio.h>

char array[8] = "12345678"; /* 8 characters - no space for '\0'! */
char secret[] = "abcdefgh"; /* A 32-bit compiler will probably put this in memory following stright on from array */

int main()
{
        printf("The array pointer gets us \"%s\" (size of array is %u)\n",array,sizeof(array));
}
--------8<--------
0
rstaveleyCommented:
[Sorry I posted that rather too late. Had it minimised in a window, while I was doing other stuff.]
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.