There are basically only two real errors in your code, plus one line that, IMHO, should certainly be changed. Here are the errors, with the solutions:
(1) As noted in the comments, the line:
char *string[50],*p;
is declaring string
as an array of 50 character pointers, whereas you just want an array of 50 characters. Use this, instead:
char string[50], *p;
(2) There are two problems with the line:
char *temp[50];
First, as noted in (1), your are declaring an array of character pointers, not an array of characters. Second, as this is a locally-defined ('automatic') variable, it will be deleted when the function exits, so your p
variable in main
will point to some memory that has been deleted. To fix this, you can declare the (local) variable as static
, which means it will remain fixed in memory (but see the added footnote on the use of static
variables):
static char temp[50];
Lastly, again as mentioned in the comments, you should not be using the gets
function, as this is now obsolete (although some compilers still support it). Instead, you should use the fgets
function, and use stdin
as the 'source file':
fgets(string, 49, stdin);/// gets() has been removed! Here, 2nd argument is max length.
Another minor issue is your use of the strlen
and strncpy
functions. The former actually returns a value of type size_t
(always an unsigned integral type) not int
(always signed); the latter uses such a size_t
type as its final argument. So, you should have this line, instead of what you currently have:
size_t size = (strlen(string) - i + 1);
Feel free to ask for further clarification and/or explanation.
EDIT: Potential Problem when using the static
Solution
As noted in the comments by Basya, the use of static data can cause issues that can be hard to track down when developing programs that have multiple threads: if two different threads try to access the data at the same time, you will get (at best) a "data race" and, more likely, difficult-to-trace unexpected behaviour. A better way, in such circumstances, is to dynamically allocate memory for the variable from the "heap," using the standard malloc
function (defined in <stdlib.h>
- be sure to #include
this header):
char* temp = malloc(50);
If you use this approach, be sure to release the memory when you're done with it, using the free()
function. In your example, this would be at the end of main
:
free(p);