0

I wrote a c code like this:

#include <stdio.h>
#include <stdlib.h>


int main()
{
    char* string;
    char n;
    while(scanf("%s",string)!=EOF){
        
        printf("\n%s\n",string);
    }

    return 0;
}

it shows an error by keep printing null. However it works when I change the char* string; into char string[50]; What is the reason behind this?

The char string[n] is able to reprint whatever I write on the terminal

  • After the `char* string;` declaration, what memory is the pointer pointing to? – Adrian Mole Mar 20 '23 at 07:46
  • You need to study pointers before you move on to strings. Also `n` should be type `int`. – Lundin Mar 20 '23 at 07:46
  • 1
    With your pointer variable `string`, it's not initialized. It doesn't point anywhere valid, and any attempt to dereference it will lead to *undefined behavior*. – Some programmer dude Mar 20 '23 at 07:46
  • `char string[50];` gives you memory where you can store 50 characters. `char* string;` gives you memory where you can store a char-pointer. The char pointer can then be assigned a value so that it points to memory where you can store characters. – Support Ukraine Mar 20 '23 at 07:46
  • `char *string;` allocates an uninitialized pointer. `char string[50];` allocates an array of 50 `char`s and `string` automatically decays into a pointer to the beginning of that array. – nielsen Mar 20 '23 at 07:48
  • See the first **images** in this article https://www.w3resource.com/c-programming/c-arrays-and-pointers.php they give a graphical insight, which is too often overlooked in a written explanation – LuC Mar 20 '23 at 07:57

0 Answers0