0

I expected that after

*b = a[0] 

line:

printf("%c\n", *b);

would print first character from string a. Here is my short code:

#include <stdio.h>

int main(){

    char a[20];
    char* b;

    scanf("%s", a);
    printf("a: %s\n", a);
    *b=a[0]; // I suppose something here is wrong
    printf("%c\n",*b);


    return 0;}

For input:

STRING

Output is:

a: STRING
Segmentation fault (core dumped)

As far as I know, segmentation fault occurs when we try to access to memory which isn't allocated (staticaly or dinamicaly). Here, b is pointer to char and it takes 8 bytes since my OS is 64-bit. Using *b we dereference pointer, i.e access to it's content. b has type char*, a[0] has type char and *b has type char. What's wrong?

mk1024
  • 119
  • 3
  • 3
    Sure, the pointer *itself* is 64 bits, but where does it point to? And who allocated that content? – Angew is no longer proud of SO Jan 14 '19 at 09:09
  • @Angew You are saying that even if I allocated space for pointer(by char* b), I have to allocate space for variables to which b will point? Like we call malloc to allocate space for array which has dimension n, I should in some way allocate space for this single char? – mk1024 Jan 14 '19 at 09:13
  • 1
    That's right. Well, you could make it point to something that already exists, but your line of `*b=a[0];` says "take the first element of `a` and copy to the place where `b` points". For that, it must already be pointing somewhere valid. – Blaze Jan 14 '19 at 09:19

2 Answers2

2

The issue here is that you didn't allocate any char for b to point to, yet you try to write to where b points, that's why it crashes.

You probably wanted something like:

b = &a[0]

Now b contains the address of the first element of a, that's &a[0] (which also happens to be the same address that you get with a, by the way).

Alternatively, if you want b to point to its own char and copy the first char like in your code, you could allocate memory for it beforehand:

b = malloc(sizeof(char));   // after this, *b=a[0]; can be done

And if you do that, don't forget to free that memory when you're done:

free(b);
Blaze
  • 16,736
  • 2
  • 25
  • 44
  • 1
    "_which also happens to just be `a`, by the way_" is incorrect or imprecise: the compiler _decays_ the name of the array `a` to a pointer, "which also happens to be the address of `a[0]`, by the way" – Paul Ogilvie Jan 14 '19 at 09:16
  • Thanks for the correction, I edited the answer. – Blaze Jan 14 '19 at 09:17
0

*b=a[0];

you have a crash because you dereference b while it wasn't initialized

so you write in an unknown address and by chance that address is invalid and produce the crash, the worst is when the write is possible

bruno
  • 32,421
  • 7
  • 25
  • 37