/
array_pointer.c
86 lines (75 loc) · 1.82 KB
/
array_pointer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct mystruct {
int n;
float f;
char c;
};
#define _offset_of(type, member) (( \
(size_t)&(((type *)0)->member) ))
void _strcpy(char *s, char *t)
{
while (*t++ = *s++)
;
}
void _strncpy(char *s, char *t, int n)
{
while(n) {
*t++ = *s++;
n--;
}
*t = '\0';
}
void _strcat(char *big, char *small)
{
while (*big != '\0')
big++;
while ((*big++ = *small++) != '\0')
;
}
int main(void)
{
char a[] = "Hello world\n";
char *p = a;
int i = 0;
while (p[i] != '\0') {
printf("%c", p[i]);
i++;
}
/* The source string can be const string ie, char * because we are only
* going to iterate over the string. The destination has to be a char
* array or a pointer to malloc array, ie, it should have the required
* amount of memory available with it because the data is going to be
* copied to its location
*/
char *s = "Hello";
char t[6];
_strncpy(s, t, 1);
printf("%s\n", t);
s = "World";
/* Char * can point to a new location because the pointer
* wasn't a const, only the string was.
*/
/* Testing with malloc'd block of data. We need to use strlen on char *
* to get the string size. sizeof will give the size of pointer. Also
* strlen gives length by ignoring \0, we need additional space for that
* as well, thus the +1
*/
char *mp = (char *)malloc(strlen(s) + 1);
_strcpy(s, mp);
printf("%s\n", mp);
char big[12] = "Hello";
char *small = " World";
_strcat(big, small);
printf("Concat: %s\n", big);
struct mystruct m = {
.c = 'c',
.n = 42,
.f = 3.14,
};
printf("%u is the offset of char\n", _offset_of(struct mystruct, c));
printf("%u is the offset of int\n", _offset_of(struct mystruct, n));
printf("%u is the offset of float\n", _offset_of(struct mystruct, f));
printf("%u is the size\n", sizeof(struct mystruct));
}