-5

I want to display "string pointer affected" but I get an error. Here is my code:

#include<stdio.h>

main()
{
  char* *p;

  char * s="string pointer affected";

  *p=s;

  printf("%s",*p);
}
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Sami Kobbi
  • 309
  • 1
  • 7
  • 17
  • What error you get? I tested the code and it seems working. – Ferit Dec 28 '15 at 17:47
  • An understanding of pointers & how to dereference them would avoid this problem. See [Evaluating the condition containing unitialized pointer - UB, but can it crash?](http://stackoverflow.com/questions/22465371/evaluating-the-condition-containing-unitialized-pointer-ub-but-can-it-crash/22466225#22466225) for an explanation. – Mogsdad Dec 29 '15 at 16:05

4 Answers4

6

p doesn't point to any known location, so writing to *p is a bad idea.

You mean to say:

p = &s;
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
5

You dereference a pointer which is not initialized , which will cause undefined behaviour . This is problem -

*p=s;
ameyCU
  • 16,489
  • 2
  • 26
  • 41
4

You are using an uninitialized variable in the line below and in the printf statement. If you replace

*p = s;

with

p = &s;

then it will work.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

Try:

#include<stdio.h>

main()
{
    char *p; // <--------------------------

    char *s="string pointer affected";

    printf("===== s=%p\n", s);

    p=s;

    printf("===== p=%p\n", p);

    printf("%s\n", p);
}

The problem with the original code is that p is uninitialized. So you cannot dereference it.

If you do want to use a pointer to a pointer, allocate the pointer first, and then take its address.

#include<stdio.h>

main()
{
    char *q;

    char **p = &q;

    char *s="string pointer affected";

    *p=s;

    printf("%s\n", *p);
}
Ziffusion
  • 8,779
  • 4
  • 29
  • 57