sizeof
a pointer simply gives you 8 or 4 (depending on your word size). So to get the length of a string, use strlen()
from <string.h>
. Also, you needn't cast the return value from malloc. So you'd get:
array[pos] = malloc(strlen(s)+1);
Notice that the dereferencing was removed, since it's already dereferenced.
Also, the function is strcpy()
not strcopy()
. strcpy()
is declared in <string.h>
. But strcpy()
may lead to buffer overflows, consider making your own:
int safecpy(char *s, const char *t, size_t siz)
{
size_t i;
for (i = 1; (*s = *t) && i < siz; ++i, s++, t++)
;
s[i] = 0; /* null terminate the string */
return i;
}
C arrays do not know their own size; So pass it as a separate argument. It is recommended that sizes are represented with size_t
and not int
.
Finally, print error messages to stderr
, so they don't get pipelined into another program or redirected into a file:
else fprintf(stderr, "Position exceeds dimensions of array.");