Doubt char C pointer

Asked

Viewed 473 times

1

Hello. I need to make a pointer char point to a memory position holding a phrase, in C.

I’m doing like this:

char *ptr;
char array[3] = {'o','l','a'};
ptr = &array;

But I don’t understand what’s wrong, I also don’t know how to program in C. Can anyone help? And I can’t use the library string.h.

3 answers

4

In C/C++, the name of the array is a pointer to the first element of the array, so you can do the following:

ptr = array;

Another thing, if you want to save a string in a character array, don’t forget the terminator '\0', otherwise things can happen that are not expected.

char *ptr;
char array[] = {'o','l','a', '\0'};
char outroArray[] = "Ola"; // também funciona
ptr = array;
  • an addendum. With this, you can use this new variable as the array, remembering that you can use ptr[index]. To know the size of your array, for a future query, you can use sizeof , that is: int tam = sizeof(array)/sizeof(array[0]), will determine the size of your array, in case the total size of the array has been divided by the bit size of each element of the array, this way you can know the size of an array of a struct or class for example.

3

In its code snippet, array is already of a ptr-compatible type.

So the error is in using the operator & on the last line.

This operator takes the value of the memory address where the array variable resides, which by itself is a pointer.

In short, you are assigning the value of a char pointer to a char pointer. Which is semantically incorrect, but the compiler won’t warn you of this error.

To fix just remove & like this:

ptr = array;

Another observation: the strings in C must be terminated with the null character ' 0' which is numerically zero. Several functions use it as a marker to mark the end of the string.

1

Try this:

char *ptr = "Ola";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.