Let us see what gcc
has to say about your code:
gcc -Wall test.c -o test
test.c: In function ‘function1’:
test.c:8:25: warning: comparison between pointer and integer
while (newstring[i] != NULL) {
^~
test.c:9:7: warning: implicit declaration of function ‘strcpy’ [-Wimplicit-function-declaration]
strcpy(dest, newstring[i]);
^~~~~~
test.c:9:7: warning: incompatible implicit declaration of built-in function ‘strcpy’
test.c:9:7: note: include ‘<string.h>’ or provide a declaration of ‘strcpy’
test.c:9:20: warning: passing argument 2 of ‘strcpy’ makes pointer from integer without a cast [-Wint-conversion]
strcpy(dest, newstring[i]);
^~~~~~~~~
test.c:9:20: note: expected ‘const char *’ but argument is of type ‘char’
test.c: In function ‘main’:
test.c:19:20: warning: comparison between pointer and integer
while (dest[i] != NULL) {
^~
test.c:20:22: warning: format ‘%s’ expects argument of type ‘char *’, but argument 3 has type ‘int’ [-Wformat=]
printf ("[%d] %s\n", i, dest[i]);
^
test.c: At top level:
test.c:3:6: warning: array ‘dest’ assumed to have one element
char dest[];
^~~~
As you can see there are so many warnings to take care of.
Take warnings seriously and fix them.
Doing that the code could be:
#include <stdio.h>
char dest[32];
int function1(char* newstring) {
// Or simply use strcpy instead of a loop...
int i = 0;
while(newstring[i] != '\0')
{
dest[i] = newstring[i];
++i;
}
dest[i] = '\0';
return 0;
}
int main() {
char* test="newstring";
function1(test);
int i = 0;
while (dest[i] != '\0') {
printf ("[%d] %c\n", i, dest[i]);
++i;
}
return 0;
}
Output:
[0] n
[1] e
[2] w
[3] s
[4] t
[5] r
[6] i
[7] n
[8] g
note You should also check for buffer overflow, i.e. that i
is always less than 32. For clarity I omitted that but make sure to add that before the code is considered done..