Question

So basically strcpy assigns the address of the 2nd argument to the 1st, but how does it do it with an array as the first argument? like in my program, i tried changing the address of the array but unfortunately it wont compile. So I had to resort to making a character pointer variable to assign the return value of capitalize. Is there something I'm misunderstanding?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char string[20];
char *Capitalize(char *str)
{
    int i;
    char *temp;
    temp = malloc(sizeof(char)*(int)(strlen(str)+1));
    for(i = 0;i < strlen(str);i++)
    {
        if(*(str+i) >= 'a' && *(str+i)<= 'z')
            *(temp+i) = *(str+i) - 32;
        else
            *(temp+i) = *(str+i);
    }
    *(temp+i) = '\0';
    return temp;
}
int main(void)
{
    string word;
    printf("Enter word to capitalize: ");
    scanf("%19s",word);
    word = Capitalize(word);
    printf("%s",word);
    return 0;
}
Was it helpful?

Solution

strcpy() makes a copy, just like the name implies. it's perfectly legal to copy a string in to an array.

When you make an initialization of an array such as:

char myarr[] = "hello";

You're actually copying the characters into the array.

You seem to be confusing arrays with pointers (see here for some reason you can't treat them the same)

OTHER TIPS

In C, qualifying an array by name without an indexer, is equivalent to specifying a pointer to the memory address of the first element in the array, that is why you can pass as a parameter an array to functions like strcpy.

char * strcpy ( char * destination, const char * source );

strcpy will copy whatever series of characters are found, starting at memory address specified by source, to the memory address specified by destination, until a null character (0) is found (this null character is also copied to the destination buffer).

The address values specified in the parameters are not modified, they just specify from where in memory to copy and where to. It is important that destination is pointing to a memory buffer (can be a char array or a block of memory requested via malloc) with enough capacity for the copied string to fit, otherwise a buffer underrun will occur (you will write characters past the end of your buffer) and your program might crash or behave in a weird way.

Hope I have been clear and not confused you more with my explanation ;)

The thing you seem to be missing is that in c/c++ strings ARE arrays, in most practical respects declaring

char c[] = "hello";

and

char* c = "hello";

is the same thing, all strcpy does is copy the characters into the destination memory, whether that memory is allocated as an array (presumably on the stack) or pointer (presumably on the heap);it does not make a difference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top