I canโ€™t understand why the C pointer is not working

Forgive me if this is a simple mistake, but I'm just learning C at the moment, and I just made a trivial program to understand the meaning of pointers.

I have a simple piece of code that gives the result that I expect

int x = 4; int *p; p = &x; printf("%d\n\n",*p); //output is 4 as expected 

But when I try to do the same with char array, although I follow the same logic ...

 char x[] = "Hello, Stack Overflow!"; char *p[]; p = &x; printf("%s\n\n",*p); //this gives me an error when compiling as follows // // run.c:15: error: incompatible types when assigning to type 'char *[1]' from type 'char (*)[23]' 
+4
source share
6 answers

A few mistakes. First, char *p[] does not declare an array pointer (what do you think it does) - it rather declares an array of char pointers.

Secondly, since x is an array, &x will be evaluated with the same numeric value as x (since arrays cannot be passed by value, only by a pointer, they are divided by pointers when passing the function), what you need to do is rather

 const char *x = "Hello SO!"; const char **p = &x; printf("%s\n", *p); 

This is a simple solution (creating a string literal, i.e. an array from char s, decaying to a pointer). There is another solution that requires a little more thought. From the compiler error message, you can see that type &x is equal to char (*)[] . So you should declare a pointer to an array here:

 char x[] = "Hello SO!"; // x is a char array char (*p)[] = &x; // p is a pointer to a char array printf("%s\n", *p); // printf accesses *p, so it prints the underlying char array - correct! 
+2
source

To create a pointer to an array, you must explicitly say this, since the index operator takes precedence over the dereference operator.

 char x[] = "Hello, there"; char (*p)[sizeof(x)/sizeof(*x)] = &x; 

What you say here is that dereferencing first, and then applying the index (*p)[i] should give char . As others have stated, your code declares an array of pointers to char .

+2
source

char *p[] means that p is an array of character pointers, not a pointer to an array. You must save p char *p , then it will work.

+1
source

Change char *p[] to char p[] or char *p . char *p[] is equal to char **p .

+1
source
 #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char x[] = "Hello, Stack Overflow!"; char *p; int len = strlen(x); p = malloc(len * sizeof(char) +1); strcpy(p,x); printf("%s\n\n",p); return 0; } 
+1
source

x here is a pointer in itself (pointer to the first element of the array). If you put only char *p and p = x , it should work.

-1
source

Source: https://habr.com/ru/post/1438200/


All Articles