I have the following C code:
person->title
The title is a three byte char array. All I want开发者_如何学C to do is print those three bytes. I can't use the string formatter with printf because there is no null byte.
How can I print this out without having to copy it or add a null byte to it?
Thanks in advance!
UPDATE
Turns out it's not an array, just three adjacent bytes. If I try to compile with the code suggested:
person->title[0]
It fails with the error:
test.c:46: error: subscripted value is neither array nor pointer.
printf("%c%c%c",person->title[0],person->title[1],person->title[2]);
Please try this....
char *a = &(person->title);
printf("%c %c %c", *a, *(a+1) , *(a+2));
EDIT
Based on 20 fields in the struct it`s much more simple mate, contiguous memory allocation takes place in case of struct
eg:
struct test {
// Suppose the elements of the struct are only title and name each having 3 bytes
}*person;
// The first 3 bytes are w.r.t title and the very next 3 is allocated to name, note for
// struct it`s stored as contiguous memory allocation
// code can be rewritten as - to display title and name
char *a = &(person->title);
printf("Title : %c%c%c", *a, *(a+1), *(a+2));
printf("Name : %c%c%c", *(a+3), *(a+4), *(a+5));
You could use something like:
printf("%c%c%c", person->title[0], person->title[1], person->title[2]);
if you are sure the three bytes are filled. If it could be shorter than three bytes, try something like:
for (int i=0; (i<3) && (person->title[i] != 0); i++)
printf("%c", person->title[i]);
For structs - you could exploit the fact that the memory will be allocated as contiguous bytes. You could also use fwrite() to control exactly how many bytes are written (using "stdout" as file pointer if you want it printed to the terminal).
e.g.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _test
{
char title[3];
char job[4];
char other[5];
} Test;
int main(int argc, char* argv)
{
Test test;
strcpy(test.title,"MR_");
strcpy(test.job,"1234");
strcpy(test.other,"OTHER");
fwrite(&test,1,sizeof(Test),stdout);
printf("\n");
}
Will output:
MR_1234OTHER
精彩评论