Oh, you are a bit confused. First, A pointer, is a pointer, is a pointer, not a long and short pointer (anymore) and they are all the same size (generally 8-bytes
on x86_64
and 4-bytes
on x86
).
Your array
points to a null-terminated string literal, containing an apparent encoded date of Jan. 1, 2008. The numeric value 20080101
is easily within the size of an int
or unsigned
on any system and that is irrelevant to allocating storage for it (unless you are on a `16-bit system).
If you want to convert the string
to a long
, you can use strtol
, e.g.:
long myval = strtol (array, NULL, 10);
for base 10
conversion. The second parameter (above NULL
) is actually an endptr
that on successful conversion returns a pointer to the next character in array
following the number converted (if the string contains additional characters). You will need to include <stdlib.h>
to use strtol
.
As for your cast question, if you have array
and it is passed as void
, e.g.
long *somefunction (void *value, long *myval, ...)
Inside some function, you will need to do two things for conversion:
*myval = strtol (value, NULL, 10);
return myval;
Or, if you just need to create a pointer to long from myval
, simply create the pointer:
long *lpointer = &myval;
Allocating Storage for array
When you allocate storage dynamically for any string, you need the length of the string (+ 1
for the null-terminator). Here is where you need to understand what sizeof
will return and what strlen
will return. If you take sizeof anypointer
, you do not get the length, you get the pointer size (8-bytes
, etc..). When you use sizeof dereferenced pointer
you get the type size
for the type pointed to (e.g. sizeof *somelongpointer
will give you the storage size for a long
on your system)
If you are copying the string, it is better to include <string.h>
and then:
size_t len = strlen (array);
Then you are ready to allocate storage:
char *mycopy = malloc (len * sizeof *array + 1);
strncpy (mycopy, array, len * sizeof *array + 1);
mycopy
then holds the contents of array
. Since it was dynamically allocated, you should free it when you no longer need it (e.g. free (mycopy);
)
If your intent was to create a pointer to type long and dynamically allocate storage for the long
, then you need sizeof
to determine the size of a long on your system. e.g.
long *mylong = malloc (sizeof *mylong);
then, (using the same somefunction
example):
*mylong = strtol ((char *)value, NULL, 10);
return mylong;
Sorry for the confusion, but that should about cover all cases :)
.