DEV Community

DEV Community

Aniket Bhattacharyea

Posted on Sep 9, 2021

(Almost) Everything You Need To Know About Pointers in C

When I was first starting out with C, pointers were something that confused me the most. I was scared of pointers and could never understand how to use them.

No, I didn't say that! In fact, pointers have always been intuitive to me. But most of the students starting to learn C are put off by the idea of pointers. It is one of those areas of C which are not explained properly to students. resulting in many misconceptions about them.

In this huge post, I have compiled almost everything that is fundamental to pointers. Of course, it is a huge topic, and it's not possible to cover the entirety of it in one post, but once you know these fundamentals, you'll be able to use them more efficiently, and hopefully will be able to tackle pointers in a program.

Let's start.

Beginning With Pointer Sorcery

One fine afternoon, you are lying on your couch and thinking about the year 2038 problem and the end of the universe, and suddenly your friend calls you and asks "Hey, I want to come over and contemplate our existence, but I do not know where your house is!"

You say, "No problem buddy. I'll give you a copy of my home."

Of course, you'd never say that. Instead, you will give him your address so that he can come over. Now, you could make him a copy of your home if you're generous enough, but it takes time and defeats the purpose of your friend coming over. He wants to come to your house, not a copy.

Now think in terms of programming. At the time when C was created, memory was scarce, and being efficient was not only needed but vital. For this reason, you'd have to be really careful while dealing with memory. You'd really not like to make unnecessary copies of something.

Another case you can consider is of having "side effect" of a function. Consider this simple program.

which just prints

Even though you are calling the function f with the variable a as a parameter, and f is changing the value of a . the change doesn't show up in the original value of a , because when you are calling the function f , you are passing a copy of a , not a itself. In other terms, you are giving your friend a copy of your house.

This is desired in most cases. You don't really want your functions to accidentally change any variable where it's not supposed to. But sometimes, you actually want the function to change a variable. You have already seen such a function that can change the actual parameter.

How does scanf change the value of n ? The answer is through pointers.

Also, take a look at this classic example of swap-

It works, except it doesn't.

swap does swap the variables, but since you are making a copy of a , and b , the change doesn't show up outside the function. But we want the function to be able to change the actual variables. So we need to have some kind of way to pass the actual a and b . But in C, there is no way you can pass "actual" variables. (which is not the case in C++).

One way you might end up doing is to make a and b global

And it now works, because swap now can access a and b , but having global variables is a real bad idea .

The way? Give swap the addresses of a and b . If it has addresses of a and b , it can change them directly.

Pointers are nothing but variables that hold the address of another variable.

Now, where does this address come from? We know how bits and bytes work . The RAM of the computer can be thought of as a mess, a really long one, with lots of rooms one after another, and each byte is a room. How does the computer know which room to put data in? It gives a number to each room, and that number is the address.

When I write

I tell the compiler "Buddy, reserve one room in the mess, and call it a " . Why one room? Because the size of char is 1 byte. (Note that C's definition of a byte is basically the sizeof char , which in some rare cases might not be actually 1 byte in the machine, however, it is always 1 byte in C)

I tell the compiler to reserve the number of rooms necessary for int and call it b .

Side rant: People coming from Turbo C, and being told size of int is 2 bytes, it's not necessarily so, and probably not so in any modern computer. The C standard guarantees at least 2 bytes for int and on my machine sizeof(int) is 4, so we will stick to that for the rest of this post.

Now that our b has 4 rooms, it will stay in the rooms starting from the first one. So that when we say "address of b", we actually mean "address of the starting or ending byte of b". (See big endian and little endian . For this tutorial, let's assume it's the ending byte because it is so on my machine)

In order to get the address of b and store it, we need to use a pointer variable. Just like any other variable, a pointer also has a type, defined by the type of the thing it points to. The syntax is type_of_the_thing_it_points_to *name

Note that the asterisk need not be adjoined to the variable name. Any of these is valid -

We will prefer the 2nd syntax. We will see in a short while why.

Let's first see how to assign a value to a pointer. In order to make a pointer point to a variable, we have to store the address of the variable in the pointer. The syntax for getting the address of a variable is &variable_name .

If you run this program, you will see something like 0x7ffc2fc4ff27 . That is the value of the pointer, which is the address of the variable a (this is in hexadecimal). This value is not fixed. If you run the program again, the value will likely change, because a will be stored somewhere else.

One thing you might have noticed. Although we are declaring it as *pa , the * is not used when printing the pointer. In fact, * is not a part of the name of the pointer. The name of the pointer is just pa . The * is instead used to get the value of whatever thing the pointer is pointing to (known as dereferencing).

So, quickly revise -

  • pa is the value of the pointer, which is the address of a .
  • *pa is the value of the thing pa is pointing to, in this case a .

One more time.

  • pointer_name is the value of the pointer itself.
  • *pointer_name is the value of the thing the pointer points to.

Now, this should be clear.

Now we can rewrite the swap function as follows -

And call it with the addresses swap(&a, &b) . This works and the change shows up outside the function too. Because once you have the address of a variable, you know where it lives in memory so you can freely change it.

You might have a valid question. Since all pointers are just addresses, which are basically numbers, why is the type of the thing it points to necessary? Why do we distinguish between char* and int* although both of them are just some numbers?

The answer is clear. When you dereference a pointer, the compiler needs to know what data type is the object. Remember that address of a variable is just the address of the ending byte of the variable. In order to read the variable, the compiler needs to know its type so that it knows how many bytes to read.

Consider this program

It prints (ignore the compiler warning)

What happened here?

If you represent 1101214537 in binary it is 01000001 10100011 00110011 01001001 . So &a which is the address of a points to the byte in memory that contains the last byte of the number, which is 01001001 . When I dereference pa , the compiler sees that it points to char so it reads only one byte at that address, giving the value 01001001 which 73 , the ASCII for I . This is why the type is absolutely and you should not mix and match types unless you are absolutely sure of what you are doing. (We'll see a few examples)

Remember we told that we will prefer int *pa rather than int* pa although they are the same? The reason is to safeguard against the following common misconception. Can you find the difference?

If you are a beginner, you will assume that since int a, b makes both a and b as int , then int* pa, pb will make both pa and pb as int* . But it doesn't. The reason is * "binds" to the variable name, not the type name. If instead, you'd have written

you'd rightly conclude pa is a pointer to int, and pb is just int . Hence I prefer to write the * with the variable name, however, there are compelling reasons for the other style as well, and if you are careful enough, you can use the other style as well.

NULL and void pointer

These two are a special types of pointers in C. The Null pointer is used to denote that the pointer doesn't point to a valid memory location.

We use Null pointer in various ways, for example, to denote failure, or mark the end of a list of unknown size, etc. Dereferencing a Null pointer is undefined behavior and your program will likely crash.

Note that the Null pointer is not the same as pointer to memory address 0, although it's very likely to be so. There are exceptions, for example in small embedded devices where address 0 might be a valid location.

Void pointer is one more interesting pointer in C. Basically void pointer "throws away" the type of a pointer. It is a general-purpose pointer that can hold any type of pointer and can be cast to any type of pointer. The following are all valid -

But you can't dereference a void * because it doesn't have a type. Trying to dereference a void * will give you an error. However, you can cast it to anything you want and then dereference it, although it's not a very good idea and it violates the type aliasing rules.

Here we're removing the type of &a through p and casting it to a char * . Essentially a is getting read as a char and this prints A .

Be careful during casting. You should use void pointers only if you are absolutely sure of what you're doing.

Sometimes you'll see char * used as a generic pointer as well. This is because void * was not present in old versions of C, and some practice remains, or maybe the code needs to do pointer arithmetic on that pointer.

Generally void * i s used in places where you expect to work with pointers to multiple types. As an example, consider the famous memcpy function which copies a block of memory. Here is the signature of memcpy -

As you see, it accepts void * , which means it works with any type of pointers. As for an example (copied from cplusplus ) -

In line 15, we invoked memcpy with char * and in line 19, we invoked memcpy with a pointer to structure, and they both work.

Pointer arithmetic

Since pointers are just like other variables, you'd expect that we should be able to do arithmetic with them. We can, but there's a catch. First of all, we are only allowed these 2 operations -

  • Addition (and hence subtraction) of an integer constant to a pointer.
  • Subtraction of two pointers of the same type.

Let's see them one by one

This prints

Strangely, it seems pa+1 increments the pointer by 4, and not by 1. The reason lies in the datatype of the thing it points to, in this case, int . Remember that a pointer must always point to something. When you increment the pointer by 1, it points to the next thing.

In this case, pa points to an int . Where is the next int ? After 4 bytes of course, because the size of int is 4 bytes.

Similarly pa-1 points to the previous int which lies 4 bytes before.

By the same logic, pa+2 points to the int 2 places after a that is 4 * 2 = 8 bytes after a , and pa+n points to the integer n places after a which is 4n bytes after a .

An observant reader might have noticed that things are looking almost like an array, and he/she is not wrong completely. In a few minutes, we shall explore the idea of array using pointers. Before let's talk about the subtraction of pointers.

Similar to the previous case, although the difference between pa and pb is of 8 bytes as numbers, as pointers the difference is 2. The negative sign of pa-pb implies that pb points after pa .

To quickly summarise -

  • If I have some_data_type *p , then pa + n increments the pointer by n * sizeof(some_data_type) bytes.
  • If I have some_data_type *p, *q then p - q is equal to the difference in bytes divided by sizeof(some_data_type)

Let's consider what happens if we mix indirection and prefix or postfix increment/decrement operators. Can you guess what each of these does? I have omitted the data types so that you can't guess ;-). Assume p points to int

In order to answer, you have to remember the precedence -

  • Postfix ++ and -- have higher precedence than *
  • Prefix ++ and -- have the same precedence as * .

Since the * operator is itself a prefix, you'll never have a problem with prefix increment or decrement. You can tell just by the order of the operator. For the postfix operator, remember that postfix works first, then indirection.

So *p++ is same as *(p++) . So, the value of p will be used in the expression, then p will be incremented. So x gets the value of *p and p becomes p+1 , so that the type of x ought to be int too.

++*p will probably not arise confusion. This is the same as ++ (*p) . So, first p is dereferenced, and then ++ is applied. So whatever p was pointing to gets incremented by 1 and then it is assigned to x , and p is unchanged. So the type of x is again int .

And finally * ++p is same as * (++p) . So, first p gets incremented by 1, and then it is dereferenced. So x gets the value of whatever is this incremented pointer pointing to.

We can also compare pointers using relational operators like == , <= etc. but there's a catch. You can only compare two pointers using <=, <, >=, > if they both are pointers of the same type, and of the same array or same aggregate object. Otherwise, it is undefined behavior.

Quoting C11 -

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P . * In all other cases, the behavior is undefined. *

Take a look -

This prints Bye . Well first of all this comparison is valid since p and q are both pointers to int and also they both point to elements of the same struct . Since q was declared later in some_struct , q compares greater to p

For equality, the restriction is a bit slack. You can compare any two pointers as long as they have the same type, or one of them is a null pointer or void pointer. And they compare equal if they point to the same object, or if both are null (doesn't matter if types don't match), or if both are pointing to members of the same union.

Let's demonstrate the last point.

This prints Equal although p and q point to different things, they are within the same union.

Since pointers are just numbers, can you put any integer in them? The answer is yes, but be careful of what you put. In fact, be careful when you dereference it. If you try to dereference an invalid address, your program will likely segfault and crash.

This instantly segfaults.

Admitted to Hogwarts School Of Pointer Magic

Pointers and arrays.

Let's now move to some advanced sorcery - array and pointers.

We know that an array stores its elements contiguously in memory. Which means the elements are stored in order one after another. So if we have int arr[10] , we know arr[1] lies right after arr[0] , arr[2] lies right after arr[1] and so on. So if I have a pointer to arr[0] and I increment it by 1, it should point to arr[1] . If I increment it by 1 again, it should point to arr[2] .

In fact, there are so many similarities between arrays and pointers, that we can talk about the equivalence of arrays and pointers.

Word of caution! This does not mean arrays and pointers are the same and you can use one in place of another. This misconception is quite common and ends up being harmful. Arrays and pointers are very different things, but pointer arithmetic and array indexing are equivalent.

For starters, the name of an array "decays" into a pointer to the first element. What do I mean by that? Consider this code -

But aren't we mixing up datatypes in the case of pb ? pb is a pointer to int and arr is an array of int!

Turns out that arr is converted to a pointer to the first element. So that arr and &(arr[0]) is equivalent.

Quick note: indexing operator [] has higher precendence than * so that * arr[0] is same as * (arr[0])

Let's do even more funny stuff -

The first printf is ok. arr[1] means the 2nd element of arr .

We just reasoned about the 2nd line. pa points to the first element of arr . So pa+1 will point to the next int in memory, which is arr[1] because array elements are stored contiguously.

But in the 3rd and 4th lines, aren't we mixing up array and pointer syntax? Well, turns out that arr[i] is just the same as *(arr + i) and this is (almost) what happens internally when you write arr[i] .

Similarly *(pa + i) is the same as pa[i] . Pointer arithmetic works both on arrays and pointers. Similarly, array indexing works on both pointers and arrays.

And for the last part, arr[1] is the same as *(arr + 1) which is the same as *(1 + arr) which should be the same as 1[arr] . This is one of those weird quirks of C.

Does this mean you can mix and match pointers and arrays? The answer is a big fat no. The reason is although arr[i] and pa[i] give you the same result, i. e. the 2nd element of arr , the way they reach there is quite different.

Consider the code

Let's look at the assembly code generated by the compiler. I used Compiler Explorer . Don't worry if you can't read assembly. We'll go together.

We are interested in lines 5 and 6. Here's the related assembly for int arr[3] = {1, 2, 3} .

In case you are seeing assembly for the first time, rbp is the base pointer register that holds the memory address of the base of the current stack frame. Don't worry about what that means. For now think of rbp as a pointer variable, which points to some location in memory.

Here the contents of arr is being put in memory. For example, consider the first line. The mov instruction puts the value 1 somewhere in memory. The DWORD PTR tells that it is of size 32 bit or 4 bytes as it is an int . The syntax [rbp - 28] means the content of the memory location at the address rbp-28 . Remember that rbp is like a pointer. So it is the same as doing * (rbp - 28) .

Putting everything together, we see that the first line puts the value 1 in the memory address pointed by rbp-28 . The next value should be stored right after it, i. e. after 4 bytes. Which should be pointed by rbp-24 and indeed that is where 2 is stored. And finally, 3 is stored in the memory address pointed by rbp-20 .

So, we see that the address of the first element is rbp-28 . So we'd expect this should be reflected in the line int *pa = arr; . And indeed it is -

lea means load effective address which calculates rbp-28 and stores the address in rax rather than fetching the content of the memory address   rbp-28 and storing the content . In other words, it just copies the address of the first element in rax register and then in the memory location rbp-8 which is our pa .

Now let's look at int a = arr[1]

So here first the content of rbp-24 is loaded into eax and then stored in rbp-12 which is our a . The interesting thing to notice is that the compiler knows the first element of arr is at rbp-28 so when you write arr[1] it directly offsets the base address by and gets rbp-24`. This happens in compile time.

Now let's look at int b = pa[1];

Here we see first the value stored at rbp-8 is moved to rax . Remember this was our pa variable? So first the value stored at pa is read. Then it is offset by 1, so we get rax + 4 and we read the value at rax+4 and store it to eax . Finally, we store the value from eax to rbp-16 which is the b variable.

The noticeable difference is that it takes one extra instruction in case of pointer. Because array address is fixed, when you write arr , the compiler knows what you're talking about. But a pointer value can be changed. So when you write pa , the value of pa needs to be read first and then it can be used.

Now suppose something like this. You have two files. One contains a global array like

And in another file, you get carried away by the equivalence of array and pointer and write

In other words, you have declared arr as a pointer but defined as an array. What will happen if you write int a = arr[1] ?

The answer is - something catastrophic. Let's see why.

Let's assume the array elements are stored just like before -

But in our second file, we are doing arr[1] . So it will do something like

Can you see the problem? We are reading the content at rbp-28 , but the content is 1, the first element of the array. So, essentially we are reading the content of memory address 1+4=5 which is an invalid location!

Bottom line: Don't mix and match.

Another difference is that a pointer name is a variable, but an array name is not. So you can do pa++ and pa=arr but you cannot do arr=pa and arr++

But, there is a case where arrays and pointers are the same. That is in function parameters -

What is the difference between arr and pa ? There is no difference

The compiler treats arr and pa both as pointers, and that's about the only case you can be certain that using pointer in place of array works.

Technically, this is an illustration of an array-like syntax being used to declare pointers, rather than an example of pointers and arrays being the same.

Since pointers are like any other variable, you can have a pointer to pointers too.

Here pa is a pointer to pointer to int . So, *pa will give you a pointer to int , and finally **pa will give you an int

You can have pointers to array too. But before that, remember [] has higher precedence than *

What's the difference between pointer to an array and normal pointer? Consider

So, essentially they all point to the same location. And we already know arr is the same as a pointer to the first element. Now we see that &arr also contains the location of the first element.

Although pa and pb point to the same location, what they point to is very different. pb is a pointer to [int] so it points to a [int] which is the first element of arr whereas pa is a pointer to [array of 3 elements] so it points to an [array of 3 elements] i. e. the whole arr .

This is evident when you try to do arithmetic -

pb is a pointer to int . So pb+1 points to the next int 4 bytes after. Whereas pa is a pointer to array of 3 int . So pa+1 will point to the next array of 3 int which is 3 * 4 = 12 bytes after, and indeed, pa+1 is 12 bytes after pa . ( 0x7fff2632cc90 - 0x7fff2632cc84 = 12, these are in hexadecimal in case you're confused).

You can use a pointer to array just like a normal variable. Just remember the precedence -

The easiest way to remember is "Declaration follows usage." So the usage of a pointer will look like the way it was defined. Since we defined pa as (*pa)[] , its usage will also look the same.

One common mistake that students do, with the fact that arrays decay down to pointers in function parameters is working with multidimensional arrays.

If you have something like

you might think since array names decay to pointers in function parameter, an array of array should decay to a pointer to pointer. So you might write the declaration of f as

Unfortunately, this is wrong and will give a warning (but will compile)

What happened here? It's easy.

If an array of [int] decays down to a pointer to [int], what should an array of [array of int] decay down to? Of course a pointer to [array of int]. Remember that the size is also part of arrays type. So, in our case, arr is an array of [4 element array of int]. So, it decays down to pointer to [4 element array of int].

So you should write

Or, you can just take an array of array

Note that only the size of the rightmost column is required in the formal parameters list.

Pointers and Structures and Unions

Now we move on to struct and union . We can have pointers to them too.

Or if you prefer a typedef

An interesting situation occurs when you want to access members of struct using pointer. Suppose you want to access the member p through pa . You might do

Except, this doesn't do what you expect. The operator . has higher precedence than * so *pa.p is same as *(pa.p) . So instead of dereferencing pa and then accessing the member p , you end up accessing the member p and then dereferencing it. But pa doesn't have a member p . So, it gives a compiler error.

Instead, you want to write this

Which works the way you want. But writing this is tedious, and turns out that we write this so much that they have a special operator ->

pa -> p is same as (*pa).p but looks neat and clean.

The case of unions is a little bit involved. Quoting cppreference -

A pointer to a union can be cast to a pointer to each of its members (if a union has bit field members, the pointer to a union can be cast to the pointer to the bit field's underlying type). Likewise, a pointer to any member of a union can be cast to a pointer to the enclosing union.

What it means is that, if you have a pointer to a union, you can cast it to any of its members, and vice versa. Take a look

Here, I could cast the pointer to a to an int* and it automatically pointed to the member p . Similarly, if I had cast it to char* it would point to q .

Conversely, if I had a pointer to p , I could cast it to a pointer to some_union and it would point to a

This prints a as expected.

Ministry of Pointer Magic

Pointers and function.

It is possible to have pointers to functions too. Remember that the return type, the number of parameters it takes, and the type of each parameter - these 3 are parts of the type of a function. Hence you must provide these during pointer declaration. Also worth noting () has higher precedence than *

A pointer to function can be used just like other pointers -

This prints 2 as you'd expect.

Remember I talked about declaration follows usage? Well, turns out that in the case of pointer to functions, that rule can be ignored. For example, this works

And so does this

And weirdly enough, this too

So, in the case of functions, not only you can dereference as many times as you want, you can drop the dereferencing altogether and just use the pointer as if it were a function itself . Another one of those C quirks.

Finally, you can get wild with pointers and arrays and function like

You get the idea. Yes, it can get pretty messy, but once you know the syntax, and you have cdecl , you can easily breeze through them (or read my article )

As for how you can use a function pointer. here's an example of a simple calculator

We are storing all 4 operations in an array and when the user enters a number, we call the corresponding operation.

Qualified types

Each type in C can be qualified by using qualifiers. In particular we have 3 - const , volatile , and restrict . Here we will look at const and restrict .

Adding const to a type effectively marks it read-only, so that attempting to change the value will result in a compiler error.

Turns out, int const and const int both are valid. Now if I throw pointers into the party, I get some fun stuff

Can you guess which one is what?

To untangle this, we will remember some_data_type *p declares p to be a pointer to some_data_type

Hence, const int *p can be thought of as (const int) *p . So that p is a pointer to a const int . It means, whatever p is pointing to is a const int and you cannot change that. However, p itself is not const and can be changed.

For the second one compare it with int const p which declares p as a read only int . So, int * const p should declare p as read-only int* . This means the pointer itself is const and you can't change p , but you can change what p is pointing to.

And finally, const int * const p declares that both p and *p are read-only. So you can neither change p nor *p .

Now let's look at the restrict keyword. The restrict keyword, when applied to a pointer p , tells the compiler that as long as p is in scope, only p and pointers directly or indirectly derived from it (e. g. p+1 ) will access the thing it's pointing to.

Confused? Let's see an example.

Here is the assembly generated after enabling optimization -

The problem in this function is, p , q and v might point to the same location. So that when you do *p += *v , it might happen that *v also gets changed because p and v were pointing to the same location.

This is why *v is first loaded into eax by mov     eax, DWORD PTR [rdx] . Then it is added to *p . Again, we have to load *v because at this point, we are not sure if *v has changed or not.

Now if I update the function as follows -

the compiler is free to assume that p , q and v all point to different locations, and can load *v only once, and indeed it does

Note that it is up to the programmer to guarantee that the pointers do not overlap. In case they do, it is undefined behavior.

You can read more about restrict here .

That's probably enough for one post. To quickly recap, you have learned -

  • What pointers are.
  • How to declare and dereference pointers.
  • Pointer arithmetic.
  • Pointer comparison.
  • Pointer to array and array of pointers.
  • Pointers and arrays are not the same.
  • Pointer arithmetic and array indexing are equivalent.
  • Array in function parameter decay to a pointer.
  • Pointers to a multidimensional array.
  • Pointers to structures and unions.
  • Pointer to functions.
  • Pointer to wild exotic types.
  • const and restrict with pointers.

Note that most of these hold true in C++ also, although you have minor changes, and some new stuff like smart pointers.

Hopefully, you learned something new in this post. Subscribe to my blog for more.

Top comments (0)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

labby profile image

Mastering Docker: A Journey Through Essential Practices 🚀

Labby - Jun 29

mdarifulhaque profile image

2285. Maximum Total Importance of Roads

MD ARIFUL HAQUE - Jun 28

orix profile image

Python for Beginners

Waleedh Nihal - Jun 28

muhammedshamal profile image

WhatsApp Introduces META AI: Your New AI-Powered Chat Companion

Muhammed Shamal PV - Jun 28

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

assignment of read only location array c




Tutorials








Practice




Resources







References






Introduction Pointers, arrays, strings File IO Linked lists, trees, recursion
Arrays are useful critters that often show up when it would be convenient to have one name for a group of variables of the same type that can be accessed by a numerical index. For example, a tic-tac-toe board can be held in an array and each element of the tic-tac-toe board can easily be accessed by its position (the upper left might be position 0 and the lower right position 8). At heart, arrays are essentially a way to store many values under the same name. You can make an array out of any data-type including structures and classes.

One way to visualize an array is like this: Each of the bracket pairs is a slot in the array, and you can store information in slot--the information stored in the array is called an element of the array. It is very much as though you have a group of variables lined up side by side.



Let's look at the syntax for declaring an array. This would make an integer array with 100 slots (the places in which values of an array are stored). To access a specific part element of the array, you merely put the array name and, in brackets, an index number. This corresponds to a specific element of the array. The one trick is that the first index number, and thus the first element, is zero, and the last is the number of elements minus one. The indices for a 100 element array range from 0 to 99. Be careful not to "walk off the end" of the array by trying to access element 100!

What can you do with this simple knowledge? Let's say you want to store a string, because C has no built-in datatype for strings, you can make an array of characters.

For example: will allow you to declare a char array of 100 elements, or slots. Then you can receive input into it from the user, and when the user types in a string, it will go in the array, the first character of the string will be at position 0, the second character at position 1, and so forth. It is relatively easy to work with strings in this way because it allows support for any size string you can imagine all stored in a single variable with each element in the string stored in an adjacent location--think about how hard it would be to store nearly arbitrary sized strings using simple variables that only store one value. Since we can write loops that increment integers, it's very easy to scan through a string: Let's look at something new here: the scanf function call is a tad different from what we've seen before. First of all, the format string is '%s' instead of '%d'; this just tells scanf to read in a string instead of an integer. Second, we don't use the ampersand! It turns out that when we pass arrays into functions, the compiler automatically converts the array into a pointer to the first element of the array. In short, the array without any brackets will act like a pointer. So we just pass the array directly into scanf without using the ampersand and it works perfectly.

Also, notice that to access the element of the array, we just use the brackets and put in the index whose value interests us; in this case, we go from 0 to 9, checking each element to see if it's equal to the character a. Note that some of these values may actually be uninitialized since the user might not input a string that fills the whole array--we'll look into how strings are handled in more detail in the next tutorial; for now, the key is simply to understand the power of accessing the array using a numerical index. Imagine how you would write that if you didn't have access to arrays! Oh boy.

Multidimensional arrays are arrays that have more than one index: instead of being just a single line of slots, multidimensional arrays can be thought of as having values that spread across two or more dimensions. Here's an easy way to visualize a two-dimensional array: The syntax used to actually declare a two dimensional array is almost the same as that used for declaring a one-dimensional array, except that you include a set of brackets for each dimension, and include the size of the dimension. For example, here is an array that is large enough to hold a standard checkers board, with 8 rows and 8 columns: You can easily use this to store information about some kind of game or to write something like tic-tac-toe. To access it, all you need are two variables, one that goes in the first slot and one that goes in the second slot. You can make three dimensional, four dimensional, or even higher dimensional arrays, though past three dimensions, it becomes quite hard to visualize.

Setting the value of an array element is as easy as accessing the element and performing an assignment. For instance, for instance, or, for two dimensional arrays Let me note again that you should never attempt to write data past the last element of the array, such as when you have a 10 element array, and you try to write to the [10] element. The memory for the array that was allocated for it will only be ten locations in memory, (the elements 0 through 9) but the next location could be anything. Writing to random memory could cause unpredictable effects--for example you might end up writing to the video buffer and change the video display, or you might write to memory being used by an open document and altering its contents. Usually, the operating system will not allow this kind of reckless behavior and will crash the program if it tries to write to unallocated memory.

You will find lots of useful things to do with arrays, from storing information about certain things under one name, to making games like tic-tac-toe. We've already seen one example of using loops to access arrays; here is another, more interesting, example!

Just to touch upon a final point made briefly above: arrays don't require a reference operator (the ampersand) when you want to have a pointer to them. For example: As opposed to The fact that arrays can act just like pointers can cause a great deal of confusion. For more information please see our .







| | | |

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

C Multidimensional Arrays

Pass arrays to a function in C

C Programming Pointers

Relationship Between Arrays and Pointers

  • C Pass Addresses and Pointers
  • C Dynamic Memory Allocation
  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

  • C structs and Pointers
  • C Structure and Function

C Programming Files

  • C File Handling

C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Find Largest Element in an Array
  • Calculate Average Using Arrays
  • Access Array Elements Using Pointer
  • Add Two Matrices Using Multi-dimensional Arrays

C arrays

An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it.

How to declare an array?

For example,

Here, we declared an array, mark , of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0] , the second element is mark[1] and so on.

C Array declaration

Few keynotes :

  • Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.
  • If the size of an array is n , to access the last element, the n-1 index is used. In this example, mark[4]
  • Suppose the starting address of mark[0] is 2120d . Then, the address of the mark[1] will be 2124d . Similarly, the address of mark[2] will be 2128d and so on. This is because the size of a float is 4 bytes.

How to initialize an array?

It is possible to initialize an array during declaration. For example,

You can also initialize an array like this.

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Initialize an array in C programming

Change Value of Array elements

Input and output array elements.

Here's how you can take input from the user and store it in an array element.

Here's how you can print an individual element of an array.

Example 1: Array Input/Output

Here, we have used a  for loop to take 5 inputs from the user and store them in an array. Then, using another  for loop, these elements are displayed on the screen.

Example 2: Calculate Average

Here, we have computed the average of n numbers entered by the user.

Access elements out of its bound!

Suppose you declared an array of 10 elements. Let's say,

You can access the array elements from testArray[0] to testArray[9] .

Now let's say if you try to access testArray[12] . The element is not available. This may cause unexpected output (undefined behavior). Sometimes you might get an error and some other time your program may run correctly.

Hence, you should never access elements of an array outside of its bound.

Multidimensional arrays

In this tutorial, you learned about arrays. These arrays are called one-dimensional arrays.

In the next tutorial, you will learn about multidimensional arrays (array of an array) .

Table of Contents

  • C Arrays (Introduction)
  • Declaring an Array
  • Access array elements
  • Initializing an array
  • Change Value of Array Elements
  • Array Input/Output
  • Example: Calculate Average
  • Array Elements Out of its Bound

Video: C Arrays

Sorry about that.

Related Tutorials

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Assigning value to readonly variable during declaration

Is the following type of readonly variable definition valid?:

Is this type of declaration in combination with assignment allowed/recommended?

Vlastimil Burián's user avatar

  • What issue are you having? Yes, it is valid and allowed to assign a read-only variable in the manner that you show. What do you mean by "recommended"? There is as far as I know no other way to assign a value to a read-only variable. You certainly can't do it after tagging it as read-only... Is your question about the use of a and b ? Well, you are allowed to use them. –  Kusalananda ♦ Commented Sep 13, 2021 at 7:54
  • No issues with code, it is working fine (in this case c has a value of 2 ). Thank you for the clarification. –  Rahul Bharadwaj Commented Sep 13, 2021 at 8:06

2 Answers 2

You are allowed to use the read-only variables a and b to initialize the read-only variable c like you're showing in your question.

Generally though, you'd want to use

i.e. quoting the expansion. If the variable IFS has a value that includes the digit 2 , it could otherwise lead to an empty value in c . The value would be empty as the shell would have split the arguments to readonly on the 2 , resulting in the command

being executed.

Note that all shells don't work like this though:

Kusalananda's user avatar

I like having constants = read-only variables in my shell scripts.

That said, I already had quite a lot of trouble with them.

Alternative solution (to quoting)

I voted for the answer here now as it explains the issue rather well.

But, I deal with this issue differently: first, I assign a value to a normal variable, and after that, I mark it as read-only, an example follows:

The error message may differ slightly from shell to shell, examples:

readonly_assignment: 10: my_var: is read only
readonly_assignment: line 10: my_var: readonly variable
readonly_assignment:10: read-only variable: my_var

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged shell readonly ..

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • Integration of the product of two exponential functions
  • Is it this limit impossible or not exists?
  • "All due respect to jazz." - Does this mean the speaker likes it or dislikes it?
  • Font shape warnings in LuaLaTeX but not XeLaTeX
  • Sets of algebraic integers whose differences are units
  • Simple Container Class
  • Can front gear be replaced on a Retrospec Judd folding bicycle?
  • What kind of sequence is between an arithmetic and a geometric sequence?
  • Can I route audio from a macOS Safari PWA to specific speakers, different from my system default?
  • How do guitarists remember what note each string represents when fretting?
  • What could explain that small planes near an airport are perceived as harassing homeowners?
  • Does it matter if a fuse is on a positive or negative voltage?
  • Where can I access records of the 1947 Superman copyright trial?
  • White grids appears when export GraphicsRow to PDF
  • How to Draw Gabriel's Horn
  • How is Victor Timely a variant of He Who Remains in the 19th century?
  • Is the FOCAL syntax for Alphanumeric Numbers ("0XYZ") documented anywhere?
  • Why potential energy is not considered in the internal energy of diatomic molecules?
  • How to determine if gravity is roughly linear?
  • Exception handling: is one exception type sufficient?
  • Should I accept an offer of being a teacher assistant without pay?
  • Rear shifter cable wont stay in anything but the highest gear
  • Are both vocal cord and vocal chord correct?
  • Trying to determine what this small glass-enclosed item is

assignment of read only location array c

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

Home » C programs » C common errors programs

Error: Assignment of read-only variable in C | Common C program Errors

Here, we will learn how and when error 'assignment of read-only variable in C' occurs and how to fix it? By IncludeHelp Last updated : March 10, 2024

Error: Assignment of read-only variable in C

Error "assignment of read-only variable in C" occurs, when we try to assign a value to the read-only variable i.e. constant.

In this program, a is a read-only variable or we can say a is an integer constant, there are two mistakes that we have made:

  • While declaring a constant, value must be assigned – which is not assigned.
  • We cannot assign any value after the declaration statement to a constant – which we are trying to assign.

Consider the program:

How to fix it?

Assign value to the variable while declaring the constant and do not reassign the variable.

Correct Code

C Common Errors Programs »

Related Programs

  • Error: undefined reference to 'main' in C
  • Error: Expected ';' before 'return' in C
  • Error: expected ')' before ';' token in C
  • Error: missing terminating double quote character in C
  • Error: 'Hello'/Text undeclared while printing Hello world using printf()
  • Error: expected declaration specifies before printf in C
  • Error: expected declaration or statement at end of input in C
  • Fatal Error: stio.h: No such file or directory in C
  • Error: Invalid escape sequence in C
  • Error: Unterminated comment (Invalid comment block) in C
  • Error: Assign string to the char variable in C
  • Error: 'else' without a previous 'if' in C
  • Error: case label does not reduce to an integer constant in C
  • Error: duplicate case value in C
  • Error: Executing more than one case block in C
  • Error: switch quantity not an integer in C
  • Error: case label not within a switch statement in C
  • Error: Expected '}' before 'else' in C
  • Error: expected '=', ',', ',' 'asm' or ' _attribute_' before '
  • Error: Id returned 1 exit status (undefined reference to 'main')
  • Error: Assignment of read-only location in C

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

ValueError: assignment destination is read-only [Solved]

avatar

Last updated: Apr 11, 2024 Reading time · 2 min

banner

# ValueError: assignment destination is read-only [Solved]

The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array.

To solve the error, create a copy of the read-only array and modify the copy.

You can use the flags attribute to check if the array is WRITABLE .

Running the code sample produces the following output:

check if writeable

In your case, WRITEABLE will likely be set to False .

In older NumPy versions, you used to be able to set the flag to true by calling the setflags() method.

However, setting the WRITEABLE flag to True ( 1 ) will likely fail if the OWNDATA flag is set to False .

You will likely get the following error:

  • "ValueError: cannot set WRITEABLE flag to True of this array"

To solve the error, create a copy of the array when converting it from a Pillow Image to a NumPy array.

Passing the Pillow Image to the numpy.array() method creates a copy of the array.

You can also explicitly call the copy() method.

check if writable is set to true

You can also call the copy() method on the Pillow Image and modify the copy.

The image copy isn't read-only and allows assignment.

You can change the img_copy variable without getting the "assignment destination is read-only" error.

You can also use the numpy.copy() method.

The numpy.copy() method returns an array copy of the given object.

The only argument we passed to the method is the image.

You can safely modify the img_copy variable without running into issues.

You most likely don't want to make changes to the original image.

Creating a copy and modifying the copy should be your preferred approach.

If you got the error when using the np.asarray() method, try changing it to np.array() .

Change the following:

To the following:

As long as the WRITEABLE flag is set to True , you will be able to modify the array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • TypeError: Object of type ndarray is not JSON serializable
  • ValueError: numpy.ndarray size changed, may indicate binary incompatibility
  • NumPy RuntimeWarning: divide by zero encountered in log10
  • ValueError: x and y must have same first dimension, but have shapes

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Compiler says "error: assignment of read

  Compiler says "error: assignment of read-only location"

assignment of read only location array c

std; main () { fstream file; string name; cout << << endl; cin >> name; file.open (name.c_str() , ios::in | ios::out | ios::app); }
std; Transform : FileFilter { lines [1000]; : transform ( , fstream &) ; }; Transform::transform ( ch, fstream &file) { n = 0; m = 0; b = 0; byte; (!file.eof()) { file.get (byte); lines[n] = byte; n++; } file.seekg (0, ios::beg); (!file.eof()) { lines[m] = toupper(lines[m]); m++; } file.seekg (0, ios::beg); (!file.eof()) { cout << lines[b]; b++; } }
std; OriginalFile : FileFilter { : lines_ [1000]; : readFile (fstream &) ; }; OriginalFile::readFile (fstream & file1) { n = 0; m = 0; byte; (!file1.eof()) { file1.get (byte); lines_[n] = byte; n++; } file1.seekg (0, ios::beg); (!file1.eof()) { cout << lines_[m] << endl; m++; } }
std; FileFilter { : transform ( , fstream &) = 0; readFile (fstream &) = 0; };
But the compiler says that there is an error "assignment of read-only location".
std; FileFilter { : transform ( , fstream &) = 0; readFile (fstream &) = 0; };

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C

Const Qualifier in C

  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators
  • Assignment Operators in C
  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

The qualifier const can be applied to the declaration of any variable to specify that its value will not be changed (which depends upon where const variables are stored, we may change the value of the const variable by using a pointer). The result is implementation-defined if an attempt is made to change a const.

Using the const qualifier in C is a good practice when we want to ensure that some values should remain constant and should not be accidentally modified.

In C programming, the const qualifier can be used in different contexts to provide various behaviors. Here are some different use cases of the const qualifier in C:

1. Constant Variables

In this case, const is used to declare a variable var as a constant with an initial value of 100. The value of this variable cannot be modified once it is initialized. See the following example:

2. Pointer to Constant

We can change the pointer to point to any other integer variable, but cannot change the value of the object (entity) pointed using pointer ptr. The pointer is stored in the read-write area (stack in the present case). The object pointed may be in the read-only or read-write area. Let us see the following examples.

Example 2: Program where variable i itself is constant.

Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type.

Example 3: Program to show down qualification.

3. Constant Pointer to Variable

The above declaration is a constant pointer to an integer variable, which means we can change the value of the object pointed by the pointer, but cannot change the pointer to point to another variable.

4. Constant Pointer to Constant

The above declaration is a constant pointer to a constant variable which means we cannot change the value pointed by the pointer as well as we cannot point the pointer to other variables. Let us see with an example. 

Advantages of const Qualifiers in C

The const qualifier in C has the following advantages:

  • Improved Code Readability: By marking a variable as const, you indicate to other programmers that its value should not be changed, making your code easier to understand and maintain.
  • Enhanced Type Safety : By using const, you can ensure that values are not accidentally modified, reducing the chance of bugs and errors in your code.
  • Improved Optimization: Compilers can optimize const variables more effectively, as they know that their values will not change during program execution. This can result in faster and more efficient code.
  • Better Memory Usage: By declaring variables as const, you can often avoid having to make a copy of their values, which can reduce memory usage and improve performance.
  • Improved Compatibility : By declaring variables as const, you can make your code more compatible with other libraries and APIs that use const variables.
  • Improved Reliability : By using const, you can make your code more reliable, as you can ensure that values are not modified unexpectedly, reducing the risk of bugs and errors in your code.
Type Declaration Pointer Value Change
(*ptr = 100)
Pointing Value Change
(ptr  = &a)
int * ptr Yes Yes
const int * ptr
int const * ptr
No Yes
int * const ptr Yes No
const int * const ptr No No

This article is compiled by “ Narendra Kangralkar “.

Please Login to comment...

Similar reads.

  • C-Storage Classes and Type Qualifiers

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

【C言語】assignment of read-only location ‘xxx’

“assignment of read-only location ‘xxx'” というエラーメッセージは、読み取り専用の場所に代入しようとした場合に表示されます。

例えば、次のようなコードを書いたとします。

このコードでは、定数 x の値を 10 から 20 に変更しようとしています。しかし、定数は値を変更することができないため、このコードは “assignment of read-only location ‘x'” というエラーを引き起こします。

正しいコードは、次のようになります。

この場合、定数 x の値を変数 y にコピーし、変数 y の値を変更しています。そのため、このコードはエラーを引き起こしません。

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

assignment of read-only location of non const variable

Why does the below macro fail

This doesnt compile with the following error:

simply doing

works fine. Also I dont see anything being const here. Does anyone have any idea what I am missing here?

chrise's user avatar

will process into

which is most definitely a problem, as we're assigning to a constant string. I believe you mean

Silvio Mayolo's user avatar

  • ahhhh, right... that is it. thanks for highlighting. Been a bit blind here –  chrise Commented Oct 31, 2018 at 0:39

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Do known physical systems all have a unique time evolution?
  • Why potential energy is not considered in the internal energy of diatomic molecules?
  • How do guitarists remember what note each string represents when fretting?
  • No simple group or order 756 : Burnside's proof
  • Trying to determine what this small glass-enclosed item is
  • Can I tell a MILP solver to prefer solutions with fewer fractions?
  • Should I accept an offer of being a teacher assistant without pay?
  • Diagnosing tripped breaker on the dishwasher circuit?
  • Visit USA via land border for French citizen
  • How can a landlord receive rent in cash using western union
  • What does ‘a grade-hog’ mean?
  • Can I route audio from a macOS Safari PWA to specific speakers, different from my system default?
  • Why can't LaTeX (seem to?) Support Arbitrary Text Sizes?
  • Sangaku problem involving eight circles
  • Why was the animal "Wolf" used in the title "The Wolf of Wall Street (2013)"?
  • Have children's car seats not been proven to be more effective than seat belts alone for kids older than 24 months?
  • Predictable Network Interface Names: ensX vs enpXsY
  • Is it possible to complete a Phd on your own?
  • Is the FOCAL syntax for Alphanumeric Numbers ("0XYZ") documented anywhere?
  • How to Pick Out Strings of a Specified Length
  • DSP Puzzle: Advanced Signal Forensics
  • What was the first game to intentionally use letterboxing to indicate a cutscene?
  • Is Légal’s reported “psychological trick” considered fair play or unacceptable conduct under FIDE rules?
  • Summation not returning a timely result

assignment of read only location array c

IMAGES

  1. C++ [Error] assignment of read-only location '*(a + ((sizetype)(((long

    assignment of read only location array c

  2. 关于C指针_assignment of read-only location-CSDN博客

    assignment of read only location array c

  3. 关于C指针_assignment of read-only location-CSDN博客

    assignment of read only location array c

  4. Program to Read and Print array in C language

    assignment of read only location array c

  5. Program to Read and Print 2d Array in C Language

    assignment of read only location array c

  6. Array in C Programming: Here's How to Declare and Initialize Them?

    assignment of read only location array c

VIDEO

  1. P3

  2. Assignment Operator in C Programming

  3. Deleting element at Specific Position in array

  4. Programming Assignment: Array and object iteration Week 3

  5. Array access using pointers in C programming

  6. 39. Read and Write Text Files in C/C++ (p1)

COMMENTS

  1. c

    8. In your function h you have declared that r is a copy of a constant Record -- therefore, you cannot change r or any part of it -- it's constant. Apply the right-left rule in reading it. Note, too, that you are passing a copy of r to the function h() -- if you want to modify r then you must pass a non-constant pointer. void h( Record* r)

  2. C++ error:Assignment of read-only location

    An object of type std::initializer_list<T> is a lightweight proxy object that provides access to an array of objects of type const T. The elements of an initializer_list are always const, and thus *carteRow_iterator is const. If you want a modifiable list of objects, use std::vector or std::array. edited Nov 7, 2015 at 23:12.

  3. Error: Assignment of read-only location in C

    Error: Assignment of read-only variable in C. Error: assignment of read-only location occurs when we try to update/modify the value of a constant, because the value of a constant cannot be changed during the program execution, so we should take care about the constants. They are read-only. Consider this example:

  4. (Almost) Everything You Need To Know About Pointers in C

    char *pa = &a; // pa now contains the address of a. printf("%p", pa); // %p is the format specifier to print a pointer. If you run this program, you will see something like 0x7ffc2fc4ff27. That is the value of the pointer, which is the address of the variable a (this is in hexadecimal). This value is not fixed.

  5. Arrays in C

    Let's look at the syntax for declaring an array. 1. int examplearray[100]; /* This declares an array */. This would make an integer array with 100 slots (the places in which values of an array are stored). To access a specific part element of the array, you merely put the array name and, in brackets, an index number.

  6. How to modify a const variable in C?

    prog.c: In function 'main': prog.c:5:9: error: assignment of read-only variable 'var' Changing Value of a const variable through pointer. The variables declared using const keyword, get stored in .rodata segment, but we can still access the variable through the pointer and change the value of that variable.

  7. C Arrays (With Examples)

    Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.. Declare an Array Few keynotes:

  8. Assigning value to readonly variable during declaration

    Generally though, you'd want to use. readonly c="$(( a + b ))" i.e. quoting the expansion. If the variable IFS has a value that includes the digit 2, it could otherwise lead to an empty value in c. The value would be empty as the shell would have split the arguments to readonly on the 2, resulting in the command. readonly c=.

  9. Fill array using function. Error: assign

    arr is const, this makes it non-modifiable. change int makeSortArray (const int arr[], int count) to int makeSortArray (int arr[], int count)

  10. Error: Assignment of read-only variable in C

    prog.c: In function 'main': prog.c:6:3: error: assignment of read-only variable 'a' a=100; ^ How to fix it? Assign value to the variable while declaring the constant and do not reassign the variable.

  11. C Arrays

    Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many ...

  12. 【C言語】assignment of read-only member 'xxx'

    このクラスには、読み取り専用のメンバ変数 x が定義されています。. この変数は、クラスのコンストラクタで初期化されるだけで、後から値を変更することはできません。. そのため、次のようなコードは "assignment of read-only member 'x'" というエラーを ...

  13. ValueError: assignment destination is read-only [Solved]

    The NumPy "ValueError: assignment destination is read-only" occurs when you try to assign a value to a read-only array. To solve the error, create a copy of the read-only array and modify the copy. You can use the flags attribute to check if the array is WRITABLE. main.py. from PIL import Image.

  14. Compiler says "error: assignment of read

    One derived class uses one virtual function to get an entire copy of a file and store it in a c-string array, and the other derived class uses the second virtual function to "transform" all letters in the file to upper case (and store it in a c-string array). ... (byte); lines[n] = byte; //assignment of read only location? n++; } file.seekg (0 ...

  15. Error "assignment of read-only location

    A read-modify-write (and thus clearing all set flags) is what you have in the compiling statement: TC3 -> COUNT16.INTFLAG.reg |= TC_INTFLAG_OVF; // No compile error! better use: TC3 -> COUNT16.INTFLAG.reg = TC_INTFLAG_OVF; But obviously that only makes a difference if you are actually using other flags in the register.

  16. error: assignment of read-only location 'arguments[num_of_args + 1]'

    I am working on developing my linux cshell assignment.In order to accept a command line from the terminal and execute it i did the following assignment of the values of a character constant array like this. Code: char *const arguments[MAXLINE]; while (fgets(buf, MAXLINE, stdin) != NULL) {. int num_of_args = strlen(buf);

  17. c++

    So none of your functions match that type. What you want is typedef GUI* (*CreateGUIFunc)( std::string &filepath, int x, int y ); Next, try using the insert member function of the map instead of the subscript operator, that way you can't end up calling the constant version by accident. answered Jun 26, 2010 at 0:44.

  18. Const Qualifier in C

    ./Solution.c: In function 'main': ./Solution.c:18:10: error: assignment of read-only location '*ptr' *ptr = 100; ^ Down qualification is not allowed in C++ and may cause warnings in C. Down qualification refers to the situation where a qualified type is assigned to a non-qualified type. Example 3: Program to show down qualification.

  19. 【C言語】assignment of read-only location 'xxx'

    しかし、定数は値を変更することができないため、このコードは "assignment of read-only location 'x'" というエラーを引き起こします。. 正しいコードは、次のようになります。. const int x = 10; int y = x; y = 20; この場合、定数 x の値を変数 y にコピーし、変数 y の ...

  20. c++

    C++ error:Assignment of read-only location. 2. Why cannot assign value to non-const reference? 0. error: assignment of read-only variable. 0. Assigning value to read-only member - C++. 4. Non-const calling const member function fails with read-only location C++. Hot Network Questions