-1

I'm trying to grasp the idea of pointers but can't get the hang of it. Why does this code assign the correct value to s, but create a runtime error when I try to use it on t.

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

int main(void)
{
    char *s;
    char *t;

    printf("s: ");
    scanf("%s", s);

    printf("t: ");
    scanf("%s", t);

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1

You have dynamically allocate memory for your char pointers, Otherwise it will not work. An uninitialized pointer has garbage.

//a macro to hold the size of the array.

#define DIM 12

char *s = malloc(sizeof(char) * DIM);
char *t = malloc(sizeof(char) * DIM);

printf("s: ");
scanf("%s", s);

printf("t: ");
scanf("%s", t);

Don't forget to free the memory from the heap when you are done with it.

free(t);
free(s);

If you don't want to allocate memory on the heap then you can use char arrays which you don't have to free after using it with scanf:

char t[DIM];
char s[DIM];
MD XF
  • 7,860
  • 7
  • 40
  • 71
Seek Addo
  • 1,871
  • 2
  • 18
  • 30
1

Which book are you reading? It seems strange that your book wouldn't teach you something like this...

The idea of pointers is that they allow functions such as scanf to assign to an object they point at (hence the name, pointers tend to point at things). Like other variables, however, you need to initialise them!

Suppose you have a function add_one which adds to its argument:

void add_one(int x) {
    x++;
}

This function is useless as the changes it makes to x aren't visible to the caller, due to a concept known as pass-by-value where copies of the values passed in are made, which end up being what gets modified (and so the original remains the same).

You need to make x a pointer to make that change visible outside of add_one, and the same change was necessary for scanf.

void add_one(int *x) {
    (*x)++; // equivalent to x[0]++;
}

Of course, this won't work if x doesn't actually point to something! In your example, you've got uninitialised pointer variables; they're pointing at... nothing? anything? who cares? Make them point somewhere!

You can do this by:

  • Using the &address-of operator on a variable. For example:

    int x;
    int *pointer_to_x = &x;
    
  • Declaring an array, and using the identifier of the array, possibly in conjunction with the + addition operator to point at an element in the array. For example:

    int array[42];
    int *pointer_to_first = array + 0;
    int *pointer_to_second = array + 1;
    
  • Calling malloc, realloc, calloc or some other function that returns a pointer to a suitably sized object. For example:

    int *pointer_to_whatever = malloc(sizeof *pointer_to_whatever);
    // Remember to free(pointer_to_whatever) ONCE when you're done with it
    
autistic
  • 1
  • 3
  • 35
  • 80