"When a string constant is assigned to a pointer, the C compiler will allocate memory space to hold the string constant,store the starting address of the string in the pointer.It is important to note that the target array must have enough space to hold the string.

The declaration

char target[40];

is used instead of

char *target;

It is because the second declaration does not have space allocated to hold the string."

Let's say a target string constant is assigned to a pointer which is much longer than the string to be copied. Why is it that strncpy() still wont work?

For example(the following code is compilable),

[code]

#include <stdio.h>
#include <string.h>


main(void)
{
int n;
char *target = "Target string.(additional space)";
char *source = "Source string.";

printf("Input n:");/* n is no of characters to copy */
scanf("%d", &n);
printf("Before:\n");
/* why does the compiler recognise this as an array when it is a pointer?*/
printf("Target: %s\n",&target[0]);
printf("Source: ");
puts(source);
/* the program doesnt work even though *target have enough space to store source string */
strncpy(target,source,n);
if (target[n] != '\0')
target[n] = '\0';

printf("After:\n");
printf("Target: %s\n",target);
printf("Source: ");
puts(source);
return 0;
}

[\code]


This second example uses an array to store the target string and then assign the array to a pointer. This time, the pointer can be passed to the strncpy() and operate the copy function.

[code]

#include <stdio.h>
#include <string.h>



main(void)
{
int n;
char target[40] = "Target string.";
char *source = "Source string.";
/* pointer to point to target[40] */
char *tar = target;

printf("Input n:");
scanf("%d", &n);
printf("Before:\n");
printf("Target: %s\n",tar);
printf("Source: ");
puts(source);
/* passing tar to strncpy() */
strncpy(tar,source,n);
if (target[n] != '\0')
target[n] = '\0';

printf("After:\n");
printf("Target: %s\n",target);
printf("Source: ");
puts(source);
return 0;
}


[\code]

Sorry for the lengthy post. Hope someone could give me some guidance. Thanks![CODE]
Code:
a