Pergunta

I'm new in learning the C-Language and I have a question to pointers.

For Example if I try this:

char *pointer;
strcpy(pointer,"Hello, World!\n");
printf(pointer);

I get this Output:

Segmentation Fault

But if I try this:

char *pointer = "Hello, World!\n");
printf(pointer);

I get this:

Hello, World!

My question is why it isn't working with strcpy. The functions do the same overall.

What is the difference between the first sourcecode and the second?

It would be good if someone could explain what is happening in the memory, so that I can get a better view at this.

Foi útil?

Solução

char* pointer merely gives you a variable to use to access the memory location. You've not yet allocated any memory, so when you do the strcpy you're writing to whatever random/undefined value pointer has.

You need to do something like:

char* pointer = calloc(LEN);
if (pointer)
{
    strcpy(pointer, "Hello World");
    printf(pointer);
    free(pointer);
}

Outras dicas

The first parameter to "strcpy" should be pointing to a usable location in memory. In your first source code, you havent initialized "pointer" to anything. You should first initialize it, for example by declaring it to be an array of characters of maximum length:

char myArray[42]; // where 42 represents the maximum capacity
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top