문제

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.

도움이 되었습니까?

해결책

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);
}

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top