Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C String manipulation pointer vs array notation [duplicate]

Tags:

c

string

Why does the first version make the program crash, while the second one doesn't? Aren't they the same thing?

Pointer Notation

char *shift = "mondo";
shift[3] = shift[2];

Array Notation

char shift[] = {'m', 'o', 'n', 'd', 'o', '\0'};
shift[3] = shift[2];

MWE

int main( void )
{
    char *shift = "mondo";
    shift[3] = shift[2];

    char shift[] = {'m', 'o', 'n', 'd', 'o', '\0'};
    shift[3] = shift[2];

    return 0;
}
like image 335
Nerva Avatar asked Jan 24 '16 15:01

Nerva


People also ask

What are the advantages of using array of pointers to string instead of an array of strings?

Advantages. Unlink the two dimensional array of characters, in array of strings and in array of pointers to strings, there is no fixed memory size for storage. The strings occupy only as many bytes as required hence, there is no wastage of space.

What is the difference between a pointer and an array in C?

The main difference between Array and Pointers is the fixed size of the memory block. When Arrays are created the fixed size of the memory block is allocated. But with Pointers the memory is dynamically allocated.

Can you use array notation for pointers?

Remember that memory is a sequence of bytes. But use array notation! The name of an array can also be used as a pointer to the zero'th element of the array.

Can you use array notation with pointers in C?

Access Array Elements Using Pointers In this program, the elements are stored in the integer array data[] . Then, the elements of the array are accessed using the pointer notation. By the way, data[0] is equivalent to *data and &data[0] is equivalent to data.


1 Answers

No! This is one of the important issues in C. In the first, you create a pointer to a read-only part of memory, i.e. you can not change it, only read it. The second, makes an array of characters, i.e. a part of memory of continuous characters where you can have both read and write access, meaning you can both read and change the values of the array.

like image 110
zuko32 Avatar answered Nov 15 '22 06:11

zuko32