-2

Consider the following C code snippet:

char *sentence = NULL;
strcpy(sentence, "Helloworld");
printf("%s", sentence); 

is the code segment correct or error.
If correct what is the output?

  1. Error
  2. Helloworld
  3. NuII,Helloworld
  4. None of the above

Edited by Reverend Jim: Corrected formatting

4
Contributors
5
Replies
23
Views
3 Months
Discussion Span
Last Post by Reverend Jim
1

This is clearly a homework or interview question, so please let us know what your thoughts are first.

1

The pointer just points to NULL. It has no storage space. you need to allocate space. You could use strdup to do that. IE, sentence = strdup("helloworld"); strdup will allocate space for the string (including terminating NUL character) and copy the string to the newly allocated space that "sentence" now owns.

1

i tried. it says runtime error

Then you have your answer. Wouldn't that have been easier than asking us to do your work for you?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.