HatchJS Logo

HatchJS.com

Cracking the Shell of Mystery

Incompatible Pointer Types in C: A Guide to Fixing Errors

Avatar

Incompatible Pointer Types in C

Pointers are a powerful tool in C, but they can also be a source of errors. One common error is using an incompatible pointer type. This can happen when you try to dereference a pointer of one type with a variable of another type. For example, you might try to dereference a pointer to a char with a variable of type int. This will cause a compiler error.

In this article, we’ll take a closer look at incompatible pointer types in C. We’ll discuss what they are, why they occur, and how to avoid them. We’ll also provide some examples of incompatible pointer types in action.

By the end of this article, you’ll have a good understanding of incompatible pointer types in C and how to avoid them.

Incompatible Pointer Type Reason Solution
Dereferencing a null pointer Attempting to access the value of a pointer that has not been initialized to a valid address will result in a segmentation fault. Ensure that all pointers are initialized to a valid address before dereferencing them.
Assigning a pointer to an incompatible type Attempting to assign a pointer to a type that is not compatible with the pointer’s original type will result in a compile-time error. Ensure that the pointer’s original type and the type to which you are assigning it are compatible.
Passing a pointer to a function with an incompatible type Attempting to pass a pointer to a function with an incompatible type will result in a compile-time error. Ensure that the pointer’s original type and the function’s parameter type are compatible.

What is an incompatible pointer type?

In C, a pointer is a variable that stores the address of another variable. When you declare a pointer, you must specify the type of the variable that it points to. For example, the following declaration creates a pointer to an integer:

The pointer `p` can be used to access the value of the integer variable that it points to. For example, the following code prints the value of the integer variable that `p` points to:

c printf(“The value of the integer variable is %d\n”, *p);

However, if you try to assign a pointer of one type to a variable of another type, you will get a compiler error. For example, the following code will generate a compiler error:

c int *p; char *q;

p = q; // Error: incompatible pointer types

This is because the pointer `p` is of type `int *`, and the pointer `q` is of type `char *`. These two types are incompatible, and you cannot assign a pointer of one type to a variable of another type.

An incompatible pointer type is a pointer that is not of the same type as the variable that it points to. This can happen for a variety of reasons, such as:

* **Casting a pointer to an incompatible type.** For example, the following code casts a pointer to an integer to a pointer to a character:

c int *p = 0; char *q = (char *)p; // Error: incompatible pointer types

* **Using a pointer to an array of one type to access an element of an array of another type.** For example, the following code uses a pointer to an array of integers to access an element of an array of characters:

c int arr1[] = {1, 2, 3}; char arr2[] = {‘a’, ‘b’, ‘c’};

int *p = arr1; char c = p[0]; // Error: incompatible pointer types

* **Using a pointer to a structure of one type to access a member of a structure of another type.** For example, the following code uses a pointer to a structure of type `struct point` to access a member of a structure of type `struct circle`:

c struct point { int x; int y; };

struct circle { struct point center; int radius; };

struct point *p = &circle.center; int x = p->x; // Error: incompatible pointer types

What are the causes of incompatible pointer types?

There are a number of reasons why you might get an incompatible pointer type error. Some of the most common causes include:

  • Casting a pointer to an incompatible type. This is the most common cause of incompatible pointer type errors. When you cast a pointer to an incompatible type, you are essentially telling the compiler that you know what you are doing and that you are sure that the pointer is safe to use. However, in most cases, you are not aware of the potential dangers of casting a pointer to an incompatible type, and you are likely to make a mistake.
  • Using a pointer to an array of one type to access an element of an array of another type. This is another common cause of incompatible pointer type errors. When you use a pointer to an array of one type to access an element of an array of another type, you are essentially telling the compiler that you know that the arrays are the same size and that you are sure that the pointer is safe to use. However, in most cases, you are not aware of the potential dangers of using a pointer to an array of one type to access an element of an array of another type, and you are likely to make a mistake.
  • Using a pointer to a structure of one type to access a member of a structure of another type. This is another common cause of incompatible pointer type errors. When you use a pointer to a structure of one type to access a member of a structure of another type, you are essentially telling the compiler that you know that the structures are the same size and that you are sure that the pointer is safe to use. However, in most cases, you are not aware of the potential dangers of using a pointer to a structure of one type to access a member of a structure of another type, and you are likely to make a mistake.

Incompatible pointer types can

How to fix incompatible pointer types?

Incompatible pointer types occur when you try to assign a value of one pointer type to a variable of another pointer type. This can happen when you are trying to pass a pointer to a function that expects a different pointer type, or when you are trying to cast a pointer to a different type.

There are a few ways to fix incompatible pointer types.

  • Use a type cast. A type cast is a way to explicitly convert a value of one type to another type. To use a type cast, you use the `(type)` syntax, where `type` is the type you want to convert the value to. For example, if you have a pointer to a `char` and you want to cast it to a pointer to a `int`, you would use the following syntax:

c int *intPtr = (int *)charPtr;

  • Use a function pointer. A function pointer is a pointer to a function. You can use a function pointer to call a function with a different pointer type than the function’s declared type. To use a function pointer, you declare a variable of type `function_pointer`, and then assign the address of the function to the variable. For example, the following code declares a function pointer to a function that takes a `char` pointer and returns an `int`:

c typedef int (*MyFunction)(char *);

MyFunction myFunctionPtr = myFunction;

You can then call the function using the function pointer, like this:

c int result = myFunctionPtr(“Hello world!”);

  • Use a struct. A struct is a collection of data elements that are grouped together. You can use a struct to store data of different types in a single variable. To use a struct, you declare a struct variable, and then add the data elements to the struct. For example, the following code declares a struct called `MyStruct` that has two data elements: a `char` pointer and an `int`:

c struct MyStruct { char *str; int num; };

struct MyStruct myStruct = {“Hello world!”, 10};

You can then access the data elements of the struct using the dot operator. For example, the following code prints the value of the `str` data element of the `myStruct` variable:

c printf(“str: %s\n”, myStruct.str);

Examples of incompatible pointer types

Here are some examples of incompatible pointer types:

  • A pointer to a `char` cannot be assigned to a pointer to a `int`.
  • A pointer to a function that takes a `char` pointer cannot be called with a pointer to an `int` pointer.
  • A struct that has a `char` pointer cannot be assigned to a struct that has an `int` pointer.

In each of these cases, the compiler will generate an error when you try to compile the code.

Incompatible pointer types can be a source of errors in C programs. By understanding how to fix incompatible pointer types, you can avoid these errors and write more robust code.

Q: What is an incompatible pointer type error?

A: An incompatible pointer type error occurs when you try to use a pointer of one type with a variable of another type. For example, you might try to use a pointer to a char with a variable of type int. This error can occur for a number of reasons, but the most common is when you are trying to pass a pointer to a function that expects a different type of pointer.

Q: How can I fix an incompatible pointer type error?

A: There are a few ways to fix an incompatible pointer type error. The first is to make sure that the pointer and the variable are of the same type. If they are not, you can either cast the pointer to the correct type or change the type of the variable.

Another way to fix an incompatible pointer type error is to use a different function. If the function you are trying to call expects a different type of pointer, you can find a different function that accepts the type of pointer you have.

Finally, you can also try to use a pointer to a pointer. This means that you create a pointer to a variable of one type, and then you use that pointer to access a variable of another type. This can be a bit more complicated, but it can sometimes be the only way to fix an incompatible pointer type error.

Q: What are some common causes of incompatible pointer type errors?

A: There are a few common causes of incompatible pointer type errors. The first is when you are trying to pass a pointer to a function that expects a different type of pointer. For example, you might try to pass a pointer to a char to a function that expects a pointer to an int. This error can also occur when you are trying to access a member of a structure or class using a pointer of the wrong type.

Another common cause of incompatible pointer type errors is when you are trying to dereference a pointer that is not initialized. When you dereference a pointer, you are essentially accessing the memory that the pointer points to. If the pointer is not initialized, then you will not be able to access any memory, and you will get an incompatible pointer type error.

Finally, incompatible pointer type errors can also occur when you are trying to cast a pointer to a different type. When you cast a pointer, you are essentially changing the type of the pointer. This can be done to make the pointer compatible with a function or variable that expects a different type of pointer. However, if you cast a pointer to the wrong type, you will get an incompatible pointer type error.

Q: How can I prevent incompatible pointer type errors?

A: There are a few things you can do to prevent incompatible pointer type errors. The first is to make sure that you are using the correct types for your pointers and variables. If you are not sure what type to use, you can always check the documentation for the function or variable you are using.

Another way to prevent incompatible pointer type errors is to use a type-safe language. Type-safe languages prevent you from making mistakes with types, so you can be confident that your code will not have any incompatible pointer type errors.

Finally, you can also use a compiler that has a warning for incompatible pointer type errors. This warning will let you know if you are trying to use a pointer of one type with a variable of another type. This can help you to catch incompatible pointer type errors before they cause problems in your code.

Incompatible pointer types in C can be a common source of errors. This is because pointers are used to reference memory locations, and if the types of the pointers are not compatible, then the compiler will not be able to correctly track the memory locations that the pointers are referencing. This can lead to unexpected behavior and errors.

There are a few ways to avoid incompatible pointer types in C. One way is to use the correct type for the pointer. For example, if you are trying to reference a variable of type int, then you should use a pointer of type int*. Another way to avoid incompatible pointer types is to use the type cast operator. The type cast operator can be used to convert a pointer of one type to a pointer of another type. However, it is important to use the type cast operator correctly, as it can also lead to errors.

If you are unsure about whether or not two pointer types are compatible, then you can always check the compiler documentation. The compiler documentation will provide a list of the different types of pointers that are supported, and it will also provide information on how to use the type cast operator correctly.

By following these tips, you can help to avoid incompatible pointer types in C and ensure that your code is correct and runs without errors.

Author Profile

Marcus Greenwood

Latest entries

  • December 26, 2023 Error Fixing User: Anonymous is not authorized to perform: execute-api:invoke on resource: How to fix this error
  • December 26, 2023 How To Guides Valid Intents Must Be Provided for the Client: Why It’s Important and How to Do It
  • December 26, 2023 Error Fixing How to Fix the The Root Filesystem Requires a Manual fsck Error
  • December 26, 2023 Troubleshooting How to Fix the `sed unterminated s` Command

Similar Posts

How to fix importerror: no module named ‘pandas’.

Importing Pandas: A Guide for Beginners Pandas is one of the most popular Python libraries for data analysis. It provides a variety of tools for manipulating and exploring data, making it a powerful tool for data scientists and analysts. However, getting started with Pandas can be a bit tricky, especially if you’re not familiar with…

Runtimeerror No Running Event Loop: Causes and Solutions

Runtimeerror No Running Event Loop: What It Is and How to Fix It Have you ever been working on a Python project and suddenly received the dreaded “RuntimeError: No running event loop” error? This error can be a real pain, especially if you’re not sure what it means or how to fix it. In this…

5 Ways to Fix a ValueError: Unsupported Pickle Protocol Error

Have you ever tried to open a file with Python and gotten the error “ValueError: unsupported pickle protocol: 5”? If so, you’re not alone. This error is a common one, and it can be caused by a number of things. In this article, we’ll take a look at what causes this error and how to…

Minified React Error 130: How to Fix It

Have you ever encountered the React error 130? If so, you’re not alone. This common error can be a real pain to troubleshoot, but it’s actually pretty easy to fix. In this article, I’ll explain what the React error 130 is, why it happens, and how to fix it. I’ll also provide some tips for…

AttributeError: module cgi has no attribute escape

AttributeError: module cgi has no attribute escape If you’re a Python programmer, you’ve probably encountered the dreaded AttributeError: module cgi has no attribute escape at some point. This error occurs when you try to use the escape() function from the cgi module, but the module doesn’t have an escape attribute. This can be a frustrating…

ReferenceError: React is not defined

Are you getting a `ReferenceError: react is not defined` error in your JavaScript code? If so, you’re not alone. This is a common error that can be caused by a variety of factors. In this article, we’ll take a look at what causes the `react is not defined` error and how to fix it. We’ll…

  • Understanding Quick Sort for coding interviews
  • Understanding Insertion Sort for coding interviews
  • Understanding Bubble Sort for coding interviews
  • Understanding selection sort for coding interviews
  • Generate binary numbers using a queue

A CODERS JOURNEY

Top 20 C pointer mistakes and how to fix them

After I graduated college with a BS in Electrical Engineering, I thought that was the last time I was going to program in “C”. I could not have been more wrong. Throughout various points in my career, I’ve encountered and wrangled with a decent amount of “C” code either due to legacy or portability reasons.

Pointers are the most complicated and fundamental part of the C Programming language. Most of the mistakes I’ve made in school assignments and production code is in handling pointers. So here is my attempt to catalog some of the common and not so common mistakes – something I ca refer back to the next time I have to write production code in C. Hope it helps you as well.

Mistake # 1: Omitting the pointer “*” character when declaring multiple pointers in same declaration

Consider the following declaration:

It declares an integer pointer p1 and an integer p2 . More often than not, the intent is to declare two integer pointers.

In the test code below, the last line will result in a compile error “Error C2440 ‘=’: cannot convert from ‘int *’ to ‘int’ ”

This is a pretty basic mistake that most modern compilers will catch.

Recommended Fix:

Use the following declaration to declare two pointers of the same type:

Alternatively, use a typedef – for example,

and then, use this type when declaraing pointers:

Mistake # 2: Using uninitialized pointers

The usage of an uninitialized pointer typically results in program crashes if the pointer accesses memory it is not allowed to.

Consider the code below:

On debug builds in Visual Studio, you’ll first get the following error:

followed by:

0xcc is microsoft’s debug mode marker for uninitialized stack memory.

On release builds, you’ll encounter a runtime crash on the line :printf(“%d”, n);

Recommended Fix: Always initialize pointers to a valid value.

Mistake # 3: Assigning a pointer to an uninitialized variable

This is more dangerous, IMHO, than an uninitialized pointer.In this case, unlike an uninitialized pointer, you won’t get a crash. Instead it can lead to serious logic errors in your code.

On debug builds, it’ll result in a large negative number like “-858993460”. In VC++, the result will be 0 but that is not guaranteed by the C standard .  More specifically item 1652 in the referenced doc states that If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

Deceptively simple – do not assign pointers to uninitialized variables.

Mistake # 4: Assigning value to pointer variables

Another one of the novice errors where the IDE/compiler will most likely bail you out. Consider the code:

The problem is that p1 can contain an address of an int and not the int value itself. You’ll get a compiler error:

Assign the address of the integer variable to the pointer .

Mistake # 5: Incorrect syntax for incrementing dereferenced pointer values

If the intent is to increment a variable pointed to by a pointer, the following code fails to achieve that.

In fact, p1 now points to an undefined memory location. When you run this code, you get the following output with the first line corresponding to the value at the address p1 points to.

Recommended Fix: To increment a dereferenced pointer, use : (*p1)++;

Mistake # 6: Trying to deallocate stack memory using free()

Consider the code below where variable m is allocated on the stack.

Attempting to free memory on the stack using the free() function throws an access violation.

Memory on the stack(non-pointer variables) is done implicitly by the system. It is illegal to get memory from the stack and return it to the heap.

Recommended Fix: Use free() to deallocate memory that has been previously allocated by malloc() or one of its variants. Always remember where the memory came from – stack or heap 🙂

Mistake # 7: Dereferncing the value of a pointer after it has been freed

Consider the following code – we allocate an integre pointer, use it , free the memory associated with the pointer and then try to use the pointer again. This’ll end in undefined behavior – maybe crashes depending on the state of the system/platform.

Never use a pointer after it has been freed. A good practice is to set the pointer to NULL after it has been freed such that any attempt to use it again is caught by an access violation.A crash during development is better than undefined behavior after release 🙂

Mistake # 8 : Double free()

Calling free() on a block of memory twice will lead to heap corruption. For example, the following code results in an unhandled exception indicating heap corruption using MS VC++:

This type of issue caused a security vulnerability in zlib which you can read about here .

Do not free the same block of memory twice! Simply assign NULL to a pointer after it has been freed. Subsequent attempts to free a null pointer will be ignored by most heap managers.

Mistake # 9 : Not using sizeof() operator with malloc

If you’re implementing something in C in this day and age, most likely you’re doing it with platform portability in mind. The size of data types can vary across different platform architectures. If you write something like malloc(2), you might have trouble porting it across platforms.

Recommended Fix: Always use sizeof(type) with malloc – for example:

Mistake # 10 : Using a pointer and sizeof() to determine the size of an array

In the code below, sizeof(arr) will correctly determine the size of the char array but a pointer to the array won’t. The type of *cp is const char, which can only have a size of 1, whereas the type of arr is different: array of const char.

Recommended Fix: Never use sizeof on a pointer to an array to determine the size of the array.

Mistake # 11 : Creating garbage objects using C pointers

You need a pointer to a memory location to free / deallocate that memory. If you re-assign a pointer and there is no other pointer pointing to that memory block, you cannot deallocate that previous memory block. This causes a memory leak.

“Memory block 1” is not inaccessible because we don’t have a pointer to it. Without having a pointer to a memory block, we cannot call free() on a block and we’ve created a garbage object in that block – in other words, we leaked memory.

In general, it’s not a good idea to recycle pointer variables. Use new pointer variables where possible and remember to set a pointer variable to NULL right after it has been freed.

Mistake # 12 : Not Understanding the difference between shallow copy and deep copy

Given two pointers p and q, the assignment p = q does not copy the block of memory pointed to by q into a block of memory pointed to by p; instead it assigns memory addresses ( so that both p and q point to the same memory location; changing the value of that memory location affects both pointers).

So what just happened?

In the shallow copy case, af1 and af2 both points to the same memory location. Any change to the memory location via af2 is reflected when af1 is used.

In the deep copy case, when we modify af3 (which points to an entirely different memory block than af1), the memory block pointed by af1 is not affected.

Mistake # 13 : Freeing a memory block shared by two pointers using one of the pointers and subsequently trying to use the other pointer

In the code below,. str1 and str2 points to the same memory block – so when str1 is freed, essentially the memory block pointed to by str2 is freed. Any attempt to use str2 after str1 has been freed will cause undefined behavior. In the case of the program below – it’ll print some garbage value.

There’s really no good way around this in C except to use static analyzers. If you’re in C++, you can use shared_pointers – but use caution as advised in the linked article. . There’s also a good discussion on Stackoverflow on this topic.

Mistake # 14 : Trying to access memory locations not allocated by your code

If you have allocated a block of n objects, do not try to access objects beyond this block ( which includes any objects in locations p+n and beyond)

The statement  doubleVals[SIZE] = 25.99  is essentially writing over memory it does not own – which can cause undefined behavior in programs.

Always be aware of the bounds of memory allocated by your code and operate within those safe limits.

Mistake # 15 : Off by one errors when operating on C pointers

Given a block of memory of SIZE objects pointed to by p, the last object in the block can be retrieved by using another pointer q and setting it to (p+SIZE-1) instead of (p+SIZE).

The first print statement incorrectly prints “0” while the last element is “9”. The second print statement fixes it by accessing the last element at (q + SIZE – 1)

Carefully apply the “off by one error” rules that you learnt for array access to pointers.

Mistake # 16 : Mismatching the type of pointer and type of underlying data

Always use the appropriate pointer type for the data. Consider the code below where a pointer to an integer is assigned to a short:

Notice that it appears that the first hexadecimal digit stored at address 100 is 7 or f, depending on whether it is displayed as an integer or as a short. This apparent contradiction is an artifact of executing this sequence on a little endian machine.If we treat this as a short number and only use the first two bytes, then we get the short value of –1. If we treat this as an integer and use all four bytes, then we get 2,147,483,647.

Always use the correct pointer type for a specific data type – int* for int , double* for double etc.

Mistake # 17 : Comparing two pointers to determine object equality

Often we want to compare if the contents of two objects are same – for example check if two strings are equal.

In the code below, clearly the intent was to check if both strings are “Thunderbird”. But, we ended up comparing the memory addresses with the statement “str1 == str2”. Here str1 and str2 are essentially pointers to different memory addresses which holds the same string.

The code can be made to work as intended, i.e., compare string contents by making the following changes:

Always remember to compare the contents of the memory location pointed to by pointers instead of comparing the address of pointer themselves.

Mistake # 18 : Thinking that C arrays are pointers

While C pointers and Arrays can be used interchangeably in most situations, they are not quite the same. Here’s an example of where it is a recipe for access violation.

In File2.cpp, global_array is declared as an pointer but defined as an array in File1.cpp. At a high level, the compile generates different code for array indexing and access via pointer.

Change the declaration so it does match the definition, like:

Note: A detailed discussion is beyond the scope of this article. The best explanation of this issue I found was in the section, “Chapter 4. The Shocking Truth: C Arrays and Pointers Are NOT the Same!” in Deep C Secrets . It’s a fantastic book if you really want to become an expert C programmer – highly recommended.

Mistake # 19 : Not clearing out sensitive heap data managed through pointers

When an application terminates, most operating systems do not zero out or erase the heap memory that was in use by your application. The memory blocks used by your application can be allocated to another program, which can use the contents of non-zeroed out memory blocks. Just imagine you asked for a security question from the user and stored it in heap memory – it’s always a good idea to erase that memory block contents before returning the memory to the Operating System via free().

Mistake # 20 : Not taking time to understand C function pointers

Functions pointers are used extensively in many large scale production system. It’s also critical to understand more advanced concepts like callbacks, events in Win32 or lambdas in standard C++.

Here’s an example of function pointer in linux kernel:

If code like this makes your head swivel, no sweat – mine did too when i started my career. 🙂

The problem is that most college level C courses seldom does any deep exploration of function pointers, whereas once you’re in industry, it’s all over the place. Here is a good book that has an in-depth treatment of C function pointers : Understanding and Using C Pointers .

Final Thoughts

C is one of the oldest languages in use today. Pointers forms the heart and soul of C. Pointers are not only useful for writing production quality code but also in school for understanding the concepts behind self referential data structures like linked list and binary trees. Even if you are working in a high level language like Java or C#, an object is essentially a pointer. So, study pointers well because they keep showing up in coding interviews and tech screens – I wouldn’t be surprised if you get a question similar to the code snippets in this article and asked “what’s wrong with this piece of C code?”.

Good luck !

  • 35 things I learnt at Game Developer Conference (GDC) 2018
  • System Design Interview Concepts – CAP Theorem
  • GitHub Login
  • Twitter Login

Welcome to Coder Legion Community

With 329 amazing developers, connect with, already have an account log in.

  • Share on Facebook
  • Share on Twitter
  • Share on Reddit
  • Share on LinkedIn
  • Share on Pinterest
  • Share on HackerNews

Assignment makes integer from pointer without a cast in c

pointer assignment error

Programming can be both rewarding and challenging. You work hard on your code, and just when it seems to be functioning perfectly, an error message pops up on your screen, leaving you frustrated and clueless about what went wrong. One common error that programmers encounter is the "Assignment makes integer from pointer without a cast" error in C.

This error occurs when you try to assign a value from a pointer variable to an integer variable without properly casting it. To fix this error, you need to make sure that you cast the pointer value to the appropriate data type before assigning it to an integer variable. In this article, we will dive deeper into the causes of this error and provide you with solutions to overcome it.

pointer assignment error

What makes this error occur?

I will present some cases that triggers that error to occur, and they are all have the same concept, so if you understanded why the failure happens, then you will figure out how to solve all the cases easily.

Case 1: Assignment of a pointer to an integer variable

In this simple code we have three variables, an integer pointer "ptr" , and two integers "n1" and "n2" . We assign 2 to "n1" , so far so good, then we assign the address of "n2" to "ptr" which is the suitable storing data type for a pointer, so no problems untill now, till we get to this line "n2 = ptr" when we try to assign "ptr" which is a memory address to "n2" that needs to store an integer data type because it's not a pointer.

Case 2: Returning a Pointer from a Function that Should Return an Integer

As you can see, it's another situation but it's the same idea which causes the compilation error.  We are trying here to assign the return of getinteger function which is a pointer that conatains a memory address to the result variable that is an int type which needs an integer

Case 3: Misusing Array Names as Pointers

As we might already know, that the identifier (name) of the array is actually a pointer to the array first element memory address , so it's a pointer after all, and assigning a pointer type to int type causes the same compilation error.

The solutions

The key to avoiding the error is understanding that pointers and integers are different types of variables in C. Pointers hold memory addresses, while integers hold numeric values. We can use either casting , dereferencing the pointer or just redesign another solution for the problem we are working on that allows the two types to be the same. It all depending on the situation.

Let's try to solve the above cases:

Case 1: Solution: Deferencing the pointer

We need in this case to asssign an int type to "n2" not a pointer or memory address, so how do we get the value of the variable that the pointer "ptr" pointing to? We get it by deferencing the pointer , so the code after the fix will be like the following:

Case 2: Solution: Choosing the right data type

In this case we have two options, either we change the getinteger returning type to int or change the result variable type to a pointer . I will go with the latter option, because there are a lot of functions in the C standard library that returning a pointer, so what we can control is our variable that takes the function return. So the code after the fix will be like the following:

We here changed the result variable from normal int to an int pointer by adding "*" .

Case 3: Solution: Using the array subscript operator

In this case we can get the value of any number in the array  by using the subscript opeartor ([]) on the array with the index number like: myarray[1] for the second element which is 2 . If we still remember that the array identifier is a pointer to the array first memory, then we can also get the value of the array first element by deferencing the array identifier like: *myarray which will get us 1 .

But let's solve the case by using the subscript opeartor which is the more obvious way. So the code will be like the following:

Now the number 1 is assigned to myint without any compilation erros.

The conclusion

In conclusion, the error "assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast" arises in C programming when there is an attempt to assign a memory address (held by a pointer) directly to an integer variable. This is a type mismatch as pointers and integers are fundamentally different types of variables in C.

To avoid or correct this error, programmers need to ensure they are handling pointers and integers appropriately. If the intent is to assign the value pointed by a pointer to an integer, dereferencing should be used. If a function is meant to return an integer, it should not return a pointer. When dealing with arrays, remember that the array name behaves like a pointer to the first element, not an individual element of the array.

Please log in to add a comment.

- Sep 8, 2023
- Jun 4
- Jun 1
- May 6
- Apr 9
  • Send feedback

More From Phantom

Tips and tricks in article formatting for coderlegion, markdown divs in coderlegion, code formatting tests in coderlegion.

pointer assignment error

  • Tech Partner
  • Enterprise Software Development Article Challenge
  • Learn Delphi
  • DelphiFeeds
  • Delphi 25th Anniversary

Null Pointer Assignment Errors Explained

' src=

Author: Embarcadero USA

Article originally contributed by Borland Staff

End-of-Quarter Sale Ending Soon

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Join Our Global Developer Community

Join our email list and receive the latest case studies, event updates, product news, and much more.

  • Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder. Design. Code. Compile. Deploy. Start Free Trial Upgrade Today Free Delphi Community Edition Free C++Builder Community Edition

RAD Studio Guide For Managers

Something Fresh

What you can do with rad studio 12.2, faster delphi rtl with parallel arrays and ordered dictionaries, focus mode in rad studio 12.2: just you and your code, popular posts, announcing the availability of rad studio 12.2 athens.

' src=

Delphi 12 And C++Builder 12 Community Editions Released!

Interbase odbc driver on github, embarcadero partners with raize software for ksvc maintenance, new in rad studio 12.1: split editor views.

' src=

  • Toggle Reader Mode

Unknown Feed

Embarcadero

Embarcadero’s users understand the scalability and stability of C++ and Delphi programming, and depend on the decades of innovation those languages bring to development. Ninety of the Fortune 100 and an active community of more than three million users worldwide have relied on Embarcadero’s award-winning products over the past 30 years. Icons by Icons8.com .

© 2024 EMBARCADERO INC. ALL RIGHTS RESERVED

Useful Links

 alt=

pointer assignment error

Null Pointer Assignment Errors Explained

by Embarcadero USA Oct 19, 1993

Article originally contributed by Borland Staff

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Pointer assignment Error

  Pointer assignment Error

pointer assignment error

myClass { : std::string* field1; std::string* field2; LONG64* id; std::string* field3; std::string* field4; };
; myClass->field2= ; myClass->id= ??; myClass->field3= ; myClass->field4= ;
; myClass->field1 = myString;
; myClass->field1 = &myString;
...change the type of the fields to std::string...
wrote:
field1 isn't pointing to a string yet
(constructor call already made ​​previously)

Clang++ pointer assignment error message

Consider the following program

gcc and g++ compile this successfully. clang compiles this as a C program without issues.

When compiled as a C++ program, the following error message is shown for the last line

Both the types are the same : “pointer to an array of n integers”. So why is this an incompatible pointer assignment?

Something to do with C++/clang and variable length arrays (VLA)? If grp and ptr are defined using a constant instead of n, then there are no errors. But line 11 is not using n. It uses i which is bound by n. The first for-loop also uses i and there are no errors or warning for using grp and ptr in it.

I guess this can be fixed by dynamically allocating memory for grp and ptr. But why does clang++ say this is an incompatible pointer assignment when both the types are identical? Is there a way to circumvent this error without changing the code?

My code : https://godbolt.org/z/18obMz3cd

Thanks Karthik

Note that VLAs are not part of standard C++. And even in C, I would recommend that nobody should use them.

That said, the problem here is that every time you mention a VLA, it constructs a new distinct type, re-evaluating the size expression at that point of mention in the code. So, yes, both VLAs have size “n”, but those “n” are evaluated in different places, and thus could be different values (they won’t be, in your example, but in general they could).

The fix for your error is to use a typedef. A typedef of a VLA evaluates the size expression at the point where the typedef is created, not where it’s used. So, you can define a typedef to create the VLA type once, and then use the typedef name everywhere else, to ensure that they’ll all see the same type.

Thanks jyknight. Using typedefs worked, but only with a typecast.

Note the (row_ptr_t) in the last line. Without it, the error message persisted.

Looks like using & re-evaluated the VLA on the right side. Once the typecast was added, the error went away.

you still are making the VLA type multiple times (each typedef is a separate time), if you make the VLA type once it compiles without errors, no cast needed:

Thank @programmerjake .

FWIW, I filed Improve diagnostics with incompatible VLA types · Issue #99914 · llvm/llvm-project · GitHub because I think there’s room for improvement with the diagnostic wording around VLA types.

Related Topics

Topic Replies Views Activity
Clang Frontend 0 76 October 12, 2012
LLVM Dev List Archives 0 74 October 12, 2012
Clang Frontend 2 70 July 24, 2012
Clang Frontend 2 82 May 20, 2011
Clang Frontend 2 94 January 3, 2008

Ubuntu Forums

  • Unanswered Posts
  • View Forum Leaders
  • Contact an Admin
  • Forum Council
  • Forum Governance
  • Forum Staff

Ubuntu Forums Code of Conduct

  • Forum IRC Channel
  • Get Kubuntu
  • Get Xubuntu
  • Get Lubuntu
  • Get Ubuntu Studio
  • Get Ubuntu Cinnamon
  • Get Edubuntu
  • Get Ubuntu Unity
  • Get Ubuntu Kylin
  • Get Ubuntu Budgie
  • Get Ubuntu Mate
  • Ubuntu Code of Conduct
  • Ubuntu Wiki
  • Community Wiki
  • Launchpad Answers
  • Ubuntu IRC Support
  • Official Documentation
  • User Documentation
  • Distrowatch
  • Bugs: Ubuntu
  • PPAs: Ubuntu
  • Web Upd8: Ubuntu
  • OMG! Ubuntu
  • Ubuntu Insights
  • Planet Ubuntu
  • Full Circle Magazine
  • Activity Page
  • Please read before SSO login
  • Advanced Search

Home

  • The Ubuntu Forum Community
  • Ubuntu Specialised Support
  • Development & Programming
  • Programming Talk

[SOLVED] C - assigment makes integer from pointer without a cast warning

Thread: [solved] c - assigment makes integer from pointer without a cast warning, thread tools.

  • Show Printable Version
  • Subscribe to this Thread…
  • Linear Mode
  • Switch to Hybrid Mode
  • Switch to Threaded Mode
  • View Profile
  • View Forum Posts
  • Private Message

usernamer is offline

I know it's a common error, and I've tried googling it, looked at a bunch of answers, but I still don't really get what to do in this situation.... Here's the relevant code: Code: #include <stdio.h> #include <stdlib.h> #include <string.h> int main( int argc, char *argv[] ) { char path[51]; const char* home = getenv( "HOME" ); strcpy( path, argv[1] ); path[1] = home; return 0; } -- there is more code in the blank lines, but the issue's not there (I'm fairly sure), so didn't see the point in writing out 100 odd lines of code. I've tried some stuff like trying to make a pointer to path[1], and make that = home, but haven't managed to make that work (although maybe that's just me doing it wrong as opposed to wrong idea?) Thanks in advance for any help

r-senior is offline

Re: C - assigment makes integer from pointer without a cast warning

path[1] is the second element of a char array, so it's a char. home is a char *, i.e. a pointer to a char. You get the warning because you try to assign a char* to a char. Note also the potential to overflow your buffer if the content of the argv[1] argument is very long. It's usually better to use strncpy.
Last edited by r-senior; March 10th, 2013 at 03:03 PM . Reason: argv[1] would overflow, not HOME. Corrected to avoid confusion.
Please create new threads for new questions. Please wrap code in code tags using the '#' button or enter it in your post like this: [code]...[/code].
  • Visit Homepage

Christmas is offline

You can try something like this: Code: #include <stdio.h> #include <stdlib.h> #include <string.h> int main( int argc, char *argv[] ) { char *path; const char *home = getenv("HOME"); path = malloc(strlen(home) + 1); if (!path) { printf("Error\n"); return 0; } strcpy(path, home); printf("path = %s\n", path); // if you want to have argv[1] concatenated with path if (argc >= 2) { path = malloc(strlen(home) + strlen(argv[1]) + 1); strcpy(path, argv[1]); strcat(path, home); printf("%s\n", path); } // if you want an array of strings, each containing path, argv[1]... char **array; int i; array = malloc(argc * sizeof(char*)); array[0] = malloc(strlen(home) + 1); strcpy(array[0], home); printf("array[0] = %s\n", array[0]); for (i = 1; i < argc; i++) { array[i] = malloc(strlen(argv[i]) + 1); strcpy(array[i], argv[i]); printf("array[%d] = %s\n", i, array[i]); } // now array[i] will hold path and all the argv strings return 0; } Just as above, your path[51] is a string while path[1] is only a character, so you can't use strcpy for that.
Last edited by Christmas; March 10th, 2013 at 09:51 PM .
TuxArena - Ubuntu/Debian/Mint Tutorials | Linux Stuff Intro Tutorials | UbuTricks I play Wesnoth sometimes. And AssaultCube .
Originally Posted by Christmas You can try something like this: Code: #include <stdio.h> #include <stdlib.h> #include <string.h> int main( int argc, char *argv[] ) { char *path; const char *home = getenv("HOME"); path = malloc(strlen(home) + 1); if (!path) { printf("Error\n"); return 0; } strcpy(path, home); printf("path = %s\n", path); // if you want to have argv[1] concatenated with path if (argc >= 2) { path = malloc(strlen(home) + strlen(argv[1]) + 1); strcpy(path, argv[1]); strcat(path, home); printf("%s\n", path); } // if you want an array of strings, each containing path, argv[1]... char **array; int i; array = malloc(argc * sizeof(char*)); array[0] = malloc(strlen(home) + 1); strcpy(array[0], home); printf("array[0] = %s\n", array[0]); for (i = 1; i < argc; i++) { array[i] = malloc(strlen(argv[i]) + 1); strcpy(array[i], argv[i]); printf("array[%d] = %s\n", i, array[i]); } // now array[i] will hold path and all the argv strings return 0; } Just as above, your path[51] is a string while path[1] is only a character, so you can't use strcpy for that. Excellent point. I've basically fixed my problem by reading up on pointers again (haven't done any C for a little while, so forgot some stuff), and doing: Code: path[1] = *home; the code doesn't moan at me when I compile it, and it runs okay (for paths which aren't close to 51 at least), but after reading what you read, I just wrote a quick program and found out that getenv("HOME") is 10 characters long, not 1 like I seem to have assumed, so I'll modify my code to fix that.
Yes, getenv will return the path to your home dir, for example /home/user, but path[1] = *home will still assign the first character of home to path[1] (which would be '/').
  • Private Messages
  • Subscriptions
  • Who's Online
  • Search Forums
  • Forums Home
  • New to Ubuntu
  • General Help
  • Installation & Upgrades
  • Desktop Environments
  • Networking & Wireless
  • Multimedia Software
  • Ubuntu Development Version
  • Virtualisation
  • Server Platforms
  • Ubuntu Cloud and Juju
  • Packaging and Compiling Programs
  • Development CD/DVD Image Testing
  • Ubuntu Application Development
  • Ubuntu Dev Link Forum
  • Bug Reports / Support
  • System76 Support
  • Apple Hardware Users
  • Recurring Discussions
  • Mobile Technology Discussions (CLOSED)
  • Announcements & News
  • Weekly Newsletter
  • Membership Applications
  • The Fridge Discussions
  • Forum Council Agenda
  • Request a LoCo forum
  • Resolution Centre
  • Ubuntu/Debian BASED
  • Arch and derivatives
  • Fedora/RedHat and derivatives
  • Mandriva/Mageia
  • Slackware and derivatives
  • openSUSE and SUSE Linux Enterprise
  • Gentoo and derivatives
  • Any Other OS
  • Assistive Technology & Accessibility
  • Art & Design
  • Education & Science
  • Documentation and Community Wiki Discussions
  • Outdated Tutorials & Tips
  • Ubuntu Women
  • Arizona Team - US
  • Arkansas Team - US
  • Brazil Team
  • California Team - US
  • Canada Team
  • Centroamerica Team
  • Instalación y Actualización
  • Colombia Team - Colombia
  • Georgia Team - US
  • Illinois Team
  • Indiana - US
  • Kentucky Team - US
  • Maine Team - US
  • Minnesota Team - US
  • Mississippi Team - US
  • Nebraska Team - US
  • New Mexico Team - US
  • New York - US
  • North Carolina Team - US
  • Ohio Team - US
  • Oklahoma Team - US
  • Oregon Team - US
  • Pennsylvania Team - US
  • Texas Team - US
  • Uruguay Team
  • Utah Team - US
  • Virginia Team - US
  • West Virginia Team - US
  • Australia Team
  • Bangladesh Team
  • Hong Kong Team
  • Myanmar Team
  • Philippine Team
  • Singapore Team
  • Albania Team
  • Catalan Team
  • Portugal Team
  • Georgia Team
  • Ireland Team - Ireland
  • Kenyan Team - Kenya
  • Kurdish Team - Kurdistan
  • Lebanon Team
  • Morocco Team
  • Saudi Arabia Team
  • Tunisia Team
  • Other Forums & Teams
  • Afghanistan Team
  • Alabama Team - US
  • Alaska Team - US
  • Algerian Team
  • Andhra Pradesh Team - India
  • Austria Team
  • Bangalore Team
  • Bolivia Team
  • Cameroon Team
  • Colorado Team - US
  • Connecticut Team
  • Costa Rica Team
  • Ecuador Team
  • El Salvador Team
  • Florida Team - US
  • Galician LoCo Team
  • Hawaii Team - US
  • Honduras Team
  • Idaho Team - US
  • Iowa Team - US
  • Jordan Team
  • Kansas Team - US
  • Louisiana Team - US
  • Maryland Team - US
  • Massachusetts Team
  • Michigan Team - US
  • Missouri Team - US
  • Montana Team - US
  • Namibia Team
  • Nevada Team - US
  • New Hampshire Team - US
  • New Jersey Team - US
  • Northeastern Team - US
  • Panama Team
  • Paraguay Team
  • Quebec Team
  • Rhode Island Team - US
  • Senegal Team
  • South Carolina Team - US
  • South Dakota Team - US
  • Switzerland Team
  • Tamil Team - India
  • Tennessee Team - US
  • Trinidad & Tobago Team
  • Uganda Team
  • United Kingdom Team
  • US LoCo Teams
  • Venezuela Team
  • Washington DC Team - US
  • Washington State Team - US
  • Wisconsin Team
  • Za Team - South Africa
  • Zimbabwe Team

Tags for this Thread

View Tag Cloud

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is Off
  • HTML code is Off
  • Ubuntu Forums

Dereferencing Pointer to Incomplete Type Error in C

  • Dereferencing Pointer to Incomplete Type …

Causes of the dereferencing pointer to incomplete type Error in C

Incomplete types in c, referencing and dereferencing a pointer in c, solve the dereferencing pointer to incomplete type error in c.

Dereferencing Pointer to Incomplete Type Error in C

It is known that a pointer is used to store the address of values stored inside a variable. This pointer variable can be referenced to a variable to get its address or dereferenced to access its value.

But when this pointer needs to be seen or edited, it must be dereferenced. When this dereferencing is done through a declared but not defined type, it throws the error dereferencing pointer to incomplete type .

This error is caused when the compiler comes across a pointer being dereferenced to a struct. When the compiler moves towards the struct, it finds it incomplete, i.e., not defined properly.

The compiler throws different errors when an undefined struct is called to deference a pointer. The type of error encountered depends on the compiler used.

the dereferencing pointer to incomplete type Error in GCC Compiler

For example, an undefined struct looks like this:

In the above C program, it can be observed that a struct circle is constructed, but the struct called inside the main function has the name round .

Inside the main function, an object pointer *x is created from the struct round . Lastly, the pointer object is called.

Here, an incomplete struct is used as if it is a complete struct, which causes the compiler to throw the error.

It can be observed that the compiler throws the error dereferencing pointer to incomplete type .

Normally, C will find the name of the struct which was put in; if the original struct is not found, this would usually appear. It will also appear if you point a pointer pointed into that pointer.

This error typically appears if the name of your struct is different from the initialization of your struct in the code.

A struct can also throw errors when given an alias that the compiler cannot read, but that does not happen with every compiler.

the dereferencing pointer to incomplete type Error in Clang Compiler

This is encountered when the same code is run through a Clang compiler.

Here, the compiler calls out the incomplete struct but leaves the dereferenced pointer as a warning instead of an error.

Understanding why the error dereferencing pointer to incomplete type happens requires knowing two concepts.

  • What are incomplete types?
  • What does dereferencing a pointer mean?

A type declared but not specified is incomplete (in the case of struct types).

Typos in type names, which prevent the compiler from matching one name to the other, are a common cause of incomplete type errors in the C language (like in matching the declaration to the definition).

It is a misconception to think that an incomplete type is a missing type. Incomplete types can occur outside struct too.

Three scenarios cause incomplete type:

  • A struct type with no members.
  • A union type with no members.
  • An array that is declared but no element is inserted.

Create an Incomplete Type and Define It

A struct or a type that is similar needs to be specified with the information lacking to complete an incomplete type.

The creation and completion of the incomplete types are demonstrated in the examples below.

Declare a structure type but omit the members to produce an incomplete structure type. The x pointer in this illustration points to an incomplete structure type named library .

Declare the same structure type later in the same scope with its members provided to complete an incomplete structure type.

To create an array of incomplete types, declare an array type without specifying its repetition count. For instance:

Declare the same name later in the same scope with its repetition count set to finish an incomplete array type.

Once we have understood how incomplete types are completed, we can go to the second part of solving the dereferencing pointer to incomplete type error.

The function of a pointer is to store the address of a value, which means it stores a reference to something. The object to which a pointer point is called a pointee.

Referencing a Pointer in C

There are two distinct stages involved in allocating a pointer and a pointee to which it will point. The pointer/pointee structure can be thought of as having two levels of operation.

Everything needs to be set up on both levels for it to work. The most frequent mistake is to focus on writing code that manipulates the pointer level while neglecting to set up the pointee level.

Pointer operations that do not contact the pointees are sometimes referred to as “shallow” operations, while those that do are referred to as “deep” operations.

Consider the following code:

A pointer ptr_a is created inside the main function. This pointer is created but cannot store something unless a pointee or a memory chunk is allocated.

The allocation of memory is done by malloc , and the size given is equivalent to data type int .

Dereferencing a Pointer in C

Dereference operations begin at the pointer and follow up to the pointee. The objective could be to examine or modify the pointee state.

A pointer can only be dereferenced if it has a pointee; the pointee must also be allocated before the pointer can be made to point at it. Forgetting to set up the pointee is the most frequent mistake in pointer programs.

Failure in code to successfully dereference a pointer is the most common runtime crash. The runtime system in Java flags the issue of improper dereferences with minor warnings.

In compiled languages like C and C++, a bad dereference can cause a crash or cause spontaneous memory corruption. This makes it challenging to find pointer issues in compiled languages.

Once the memory is allocated and pointed towards pointer ptr_a , a value is stored inside it by dereferencing it.

Shared Pointers in C

When two pointers are assigned to the same pointee, they will both point there. As a result, y points to the same pointee as x when y = x .

The pointees are unaffected by pointer assignment.

It only modifies one pointer to share the same reference as another. After the pointer assignment, the two pointers are considered “sharing” the pointee.

We have understood the two concepts behind solving the dereferencing pointer to incomplete type error. We will now look at the codes that encounter the error and how to solve the issue.

The below program has a struct rectangle with an integer member length . The name of the struct is deliberately made different than the one inside the main function to create an incomplete type.

Inside the main function, the pointer *a is created and allocated memory of the struct rectangle size, and then it is pointed towards it.

Then the pointer is used to dereference the struct member length to store a value inside it. As the struct is of incomplete type, it must throw a dereferencing pointer to incomplete type error.

The incomplete type must be completed to resolve this issue, which in this case is the struct rectngle .

These changes must be made to complete an incomplete struct and dereference its members through a pointer inside the main function.

This article sheds light on the error that arises due to dereferencing pointer to incomplete type. After going through this article, the reader can easily reference and deference pointers and complete incomplete types.

Related Article - C Error

  • How to Handling Errors in C
  • C Segmentation Fault
  • A Label Can Only Be Part of a Statement and a Declaration Is Not a Statement
  • Stack Smashing Detected Error in C

pointer assignment error

  • Latest Articles
  • Top Articles
  • Posting/Update Guidelines
  • Article Help Forum

pointer assignment error

  • View Unanswered Questions
  • View All Questions
  • View C# questions
  • View C++ questions
  • View Javascript questions
  • View Visual Basic questions
  • View .NET questions
  • CodeProject.AI Server
  • All Message Boards...
  • Running a Business
  • Sales / Marketing
  • Collaboration / Beta Testing
  • Work Issues
  • Design and Architecture
  • Artificial Intelligence
  • Internet of Things
  • ATL / WTL / STL
  • Managed C++/CLI
  • Objective-C and Swift
  • System Admin
  • Hosting and Servers
  • Linux Programming
  • .NET (Core and Framework)
  • Visual Basic
  • Web Development
  • Site Bugs / Suggestions
  • Spam and Abuse Watch
  • Competitions
  • The Insider Newsletter
  • The Daily Build Newsletter
  • Newsletter archive
  • CodeProject Stuff
  • Most Valuable Professionals
  • The Lounge  
  • The CodeProject Blog
  • Where I Am: Member Photos
  • The Insider News
  • The Weird & The Wonderful
  • What is 'CodeProject'?
  • General FAQ
  • Ask a Question
  • Bugs and Suggestions

C Warning - assignment discards qualifiers from pointer target type

pointer assignment error

Add your solution here

Your Email  
Password  
Your Email  
?
Optional Password  
  • Read the question carefully.
  • Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  • If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Print

Top Experts
Last 24hrsThis month
20
10
10
-10
804
615
421
400
265

pointer assignment error

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.

I keep getting an error: incompatible pointer types passing 'string' (aka 'char *') to parameter of type 'string *' (aka 'char **')

user11913821's user avatar

This may sound mean, but the shift function is a mess. First, there's the error of the parameter mismatch. Note that declaring a string is really declaring a char * . Then, the parameter is itself an array. By declaring it with int shift(string argv[]) you've declared a pointer to a char pointer, or char ** . Next, you've used argv as the parameter name. This is a really bad practice. You think you're using the argv[] array, but you're actually declaring a shadow array - an array that has the same name, but is totally unrelated. You should use a unique parameter name. Never use any of the "reserved" or default variable names like argc or argv in a declaration. Further, if you want to pass a string as a parameter, declare it as a string var, not an array. For example, you could use int shift(string mystring)

This would help you resolve that particular error, but there are bigger issues that will likely make this a moot point.

In reading your code, it's not clear what you were trying to do. Part of it looks like it is trying to cycle through the key string to 'shift' all of it's elements. Other parts look like it was trying to change only one char and return that value to the calling function. Then, it falls apart by trying to 'shift' j, which is the index value used to control the for loop. J has nothing to do with the key or any character in the key. BTW, the for loop will only execute once because of the return statements. The program will never cycle back to the top of the for loop. In short, the shift function as written can't make up its mind what it wants to do! A rewrite is in order.

Do you want to convert a single char or all the chars in a string? Will it only be used on the key or also on the plaintext?

And then, in the main program, how are you going to switch from one char to the next in the key?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

Cliff B's user avatar

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged pset2 vigenere ..

  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • User activation: Learnings and opportunities
  • Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...

Hot Network Questions

  • Why do communists claim that capitalism began at the Industrial Revolution?
  • Score the science points in 7 Wonders
  • How do you measure exactly 31 minutes by burning the ropes?
  • Vertical alignment changes after removing \frame
  • How to format units inside math environment?
  • Can one freely add an explanation to a quotation in square brackets?
  • Which ancient philosopher compared thoughts to birds?
  • World's smallest Sudoku!
  • If I'm turning humans into crude oil, would removing their skeletons accelerate this process?
  • Propagation of Sansevieria – Is My Cutting Going to Succeed?
  • Increased thickness at the edges after "Bevel"
  • Is my TOTP key secure on a free hosting provider server with FTP and .htaccess restrictions?
  • Is it natural to say "could he" instead of "if he could"? E.g.: "Could he have cast himself in the part of Mr Copthorne, he would not have attempted…"
  • Induction proof for floor function composition
  • What is the greatest possible number of empty squares that could remain after the jumps?
  • 2 NICs, PC is trying to use wrong one
  • Why does Lebanon apparently lack aerial defenses?
  • Is mathematical Platonism possible without mind-body dualism?
  • Status of infinitesimal Hilbert's sixteenth problem
  • Is it ethical to edit grammar, spelling, and wording errors in survey questions after the survey has been administered, prior to publication?
  • is it correct to say "can you stop clinking the cup of coffee"?
  • Remove an entire inner list that has any zeros
  • What is the origin of the many extra mnemonics in Manx Software Systems’ 8086 assembler?
  • What is Poirot saying about the feather pen in "The Murder of Roger Ackroyd"?

pointer assignment error

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C.

In this article, we will discuss C pointers in detail, their types, uses, advantages, and disadvantages with examples.

What is a Pointer in C?

A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers.

As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. This size of pointers in C only depends on the system architecture.

Syntax of C Pointers

The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration.

  • ptr is the name of the pointer.
  • datatype is the type of data it is pointing to.

The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.

How to Use Pointers?

The use of pointers in C can be divided into three steps:

  • Pointer Declaration
  • Pointer Initialization
  • Pointer Dereferencing

1. Pointer Declaration

In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name.

The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.

2. Pointer Initialization

Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and then store it in the pointer variable.

We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time.

Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing

Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration.

dereferencing a pointer in c

Dereferencing a Pointer in C

C Pointer Example

Types of pointers in c.

Pointers in C can be classified into many different types based on the parameter on which we are defining their types. If we consider the type of variable stored in the memory location pointed by the pointer, then the pointers can be classified into the following types:

1. Integer Pointers

As the name suggests, these are the pointers that point to the integer values.

These pointers are pronounced as Pointer to Integer.

Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such as arrays and user-defined data types such as structures.

2. Array Pointer

Pointers and Array are closely related to each other. Even the array name is the pointer to its first element. They are also known as Pointer to Arrays . We can create a pointer to an array using the given syntax.

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

3. Structure Pointer

The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be declared in the same way as we declare the other primitive data types.

In C, structure pointers are used in data structures such as linked lists, trees, etc.

4. Function Pointers

Function pointers point to the functions. They are different from the rest of the pointers in the sense that instead of pointing to the data, they point to the code. Let’s consider a function prototype – int func (int, char) , the function pointer for this function will be

Note: The syntax of the function pointers changes according to the function prototype.

5. Double Pointers

In C language, we can define a pointer that stores the memory address of another pointer. Such pointers are called double-pointers or pointers-to-pointer . Instead of pointing to a data value, they point to another pointer.

Dereferencing Double Pointer

Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4, ******ptr5 and so on.

6. NULL Pointer

The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value.

It is said to be good practice to assign NULL to the pointers currently not in use.

7. Void Pointer

The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. They are also called generic pointers as they can point to any type and can be typecasted to any type.

One of the main properties of void pointers is that they cannot be dereferenced.

8. Wild Pointers

The Wild Pointers are pointers that have not been initialized with something yet. These types of C-pointers can cause problems in our programs and can eventually cause them to crash. If values is updated using wild pointers, they could cause data abort or data corruption.

9. Constant Pointers

In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address.

10. Pointer to Constant

The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant.

Other Types of Pointers in C:

There are also the following types of pointers available to use in C apart from those specified above:

  • Far pointer : A far pointer is typically 32-bit that can access memory outside the current segment.
  • Dangling pointer : A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer.
  • Huge pointer : A huge pointer is 32-bit long containing segment address and offset address.
  • Complex pointer: Pointers with multiple levels of indirection.
  • Near pointer : Near pointer is used to store 16-bit addresses means within the current segment on a 16-bit machine.
  • Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as possible.
  • File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C

The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is 

  • 8 bytes for a 64-bit System
  • 4 bytes for a 32-bit System

The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types.

How to find the size of pointers in C?

We can find the size of pointers using the sizeof operator as shown in the following program:

Example: C Program to find the size of different pointer types.

As we can see, no matter what the type of pointer it is, the size of each and every pointer is the same.

Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic

The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers. These operations include:

  • Increment in a Pointer
  • Decrement in a Pointer
  • Addition of integer to a pointer
  • Subtraction of integer to a pointer
  • Subtracting two pointers of the same type
  • Comparison of pointers of the same type.
  • Assignment of pointers of the same type.

C Pointers and Arrays

In C programming language, pointers and arrays are closely related. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably.

If we assign this value to a non-constant pointer of the same type, then we can access the elements of the array using this pointer.

Example 1: Accessing Array Elements using Pointer with Array Subscript

relationship between array and pointer

Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements.

Example 2: Accessing Array Elements using Pointer Arithmetic

accessing array elements using pointer arithmetic

This concept is not limited to the one-dimensional array, we can refer to a multidimensional array element as well using pointers.

To know more about pointers to an array, refer to this article – Pointer to an Array

Uses of Pointers in C

The C pointer is a very powerful tool that is widely used in C programming to perform various useful operations. It is used to achieve the following functionalities in C:

  • Pass Arguments by Reference
  • Accessing Array Elements
  • Return Multiple Values from Function
  • Dynamic Memory Allocation
  • Implementing Data Structures
  • In System-Level Programming where memory addresses are useful.
  • In locating the exact value at some memory location.
  • To avoid compiler confusion for the same variable name.
  • To use in Control Tables.

Advantages of Pointers

Following are the major advantages of pointers in C:

  • Pointers are used for dynamic memory allocation and deallocation.
  • An Array or a structure can be accessed efficiently with pointers
  • Pointers are useful for accessing memory locations.
  • Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
  • Pointers reduce the length of the program and its execution time as well.

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:

  • Memory corruption can occur if an incorrect value is provided to pointers.
  • Pointers are a little bit complex to understand.
  • Pointers are majorly responsible for memory leaks in C .
  • Pointers are comparatively slower than variables in C.
  • Uninitialized pointers might cause a segmentation fault.

In conclusion, pointers in C are very capable tools and provide C language with its distinguishing features, such as low-level memory access, referencing, etc. But as powerful as they are, they should be used with responsibility as they are one of the most vulnerable parts of the language.

FAQs on Pointers in C

Q1. define pointers..

Pointers are the variables that can store the memory address of another variable.

Q2. What is the difference between a constant pointer and a pointer to a constant?

A constant pointer points to the fixed memory location, i.e. we cannot change the memory address stored inside the constant pointer. On the other hand, the pointer to a constant point to the memory with a constant value.

Q3. What is pointer to pointer?

A pointer to a pointer (also known as a double pointer) stores the address of another pointer.

Q4. Does pointer size depends on its type?

No, the pointer size does not depend upon its type. It only depends on the operating system and CPU architecture.

Q5. What are the differences between an array and a pointer?

The following table list the differences between an array and a pointer : Pointer Array A pointer is a derived data type that can store the address of other variables. An array is a homogeneous collection of items of any type such as int, char, etc. Pointers are allocated at run time. Arrays are allocated at runtime. The pointer is a single variable. An array is a collection of variables of the same type. Dynamic in Nature Static in Nature.

Q6. Why do we need to specify the type in the pointer declaration?

Type specification in pointer declaration helps the compiler in dereferencing and pointer arithmetic operations.
  • Quiz on Pointer Basics
  • Quiz on Advanced Pointer

Similar Reads

Please login to comment....

  • How to Install & Use Kodi on FireStick
  • How to Watch NFL on NFL+ in 2024: A Complete Guide
  • Best Smartwatches in 2024: Top Picks for Every Need
  • Top Budgeting Apps in 2024
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

cppreference.com

Pointer declaration.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
Specifiers
function specifier
function specifier
(C++20)
/struct
volatile
(C++26)    
(C++11)
Declarators
Block declarations
(C++17)
(C++11)
declaration
directive
declaration (C++11)
declaration
(C++11)
Other declarations
(C++11)
(C++11)

Declares a variable of a pointer or pointer-to-member type.

Syntax Pointers Pointers to objects Pointers to void Pointers to functions Pointers to members Pointers to data members Pointers to member functions Null pointers Invalid pointers Constness Composite pointer type Defect reports See also

[ edit ] Syntax

A pointer declaration is any simple declaration whose declarator has the form

attr (optional) cv (optional) declarator (1)
nested-name-specifier attr (optional) cv (optional) declarator (2)
nested-name-specifier - a
attr - (since C++11) a list of
cv - const/volatile qualification which apply to the pointer that is being declared (not to the pointed-to type, whose qualifications are part of declaration specifier sequence)
declarator - any other than a reference declarator (there are no pointers to references). It can be another pointer declarator (pointer to pointers are allowed)

There are no pointers to references and there are no pointers to bit-fields . Typically, mentions of "pointers" without elaboration do not include pointers to (non-static) members.

[ edit ] Pointers

Every value of pointer type is one of the following:

  • a pointer to an object or function (in which case the pointer is said to point to the object or function), or
  • a pointer past the end of an object , or
  • the null pointer value for that type, or
  • an invalid pointer value .

A pointer that points to an object represents the address of the first byte in memory occupied by the object. A pointer past the end of an object represents the address of the first byte in memory after the end of the storage occupied by the object.

Note that two pointers that represent the same address may nonetheless have different values.

Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

[ edit ] Pointers to objects

A pointer to object can be initialized with the return value of the address-of operator applied to any expression of object type, including another pointer type:

Pointers may appear as operands to the built-in indirection operator (unary operator * ), which returns the lvalue expression identifying the pointed-to object:

Pointers to class objects may also appear as the left-hand operands of the member access operators operator-> and operator->* .

Because of the array-to-pointer implicit conversion, pointer to the first element of an array can be initialized with an expression of array type:

Because of the derived-to-base implicit conversion for pointers, pointer to a base class can be initialized with the address of a derived class:

If Derived is polymorphic , such a pointer may be used to make virtual function calls .

Certain addition, subtraction , increment, and decrement operators are defined for pointers to elements of arrays: such pointers satisfy the LegacyRandomAccessIterator requirements and allow the C++ library algorithms to work with raw arrays.

Comparison operators are defined for pointers to objects in some situations: two pointers that represent the same address compare equal, two null pointer values compare equal, pointers to elements of the same array compare the same as the array indices of those elements, and pointers to non-static data members with the same member access compare in order of declaration of those members.

Many implementations also provide strict total ordering of pointers of random origin, e.g. if they are implemented as addresses within continuous virtual address space. Those implementations that do not (e.g. where not all bits of the pointer are part of a memory address and have to be ignored for comparison, or an additional calculation is required or otherwise pointer and integer is not a 1 to 1 relationship), provide a specialization of std::less for pointers that has that guarantee. This makes it possible to use all pointers of random origin as keys in standard associative containers such as std::set or std::map .

[ edit ] Pointers to void

Pointer to object of any type can be implicitly converted to pointer to (possibly cv-qualified ) void ; the pointer value is unchanged. The reverse conversion, which requires static_cast or explicit cast , yields the original pointer value:

If the original pointer is pointing to a base class subobject within an object of some polymorphic type, dynamic_cast may be used to obtain a void * that is pointing at the complete object of the most derived type.

Pointers to void have the same size, representation and alignment as pointers to char .

Pointers to void are used to pass objects of unknown type, which is common in C interfaces: std::malloc returns void * , std::qsort expects a user-provided callback that accepts two const void * arguments. pthread_create expects a user-provided callback that accepts and returns void * . In all cases, it is the caller's responsibility to cast the pointer to the correct type before use.

[ edit ] Pointers to functions

A pointer to function can be initialized with an address of a non-member function or a static member function. Because of the function-to-pointer implicit conversion, the address-of operator is optional:

Unlike functions or references to functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, etc.

Note: declarations involving pointers to functions can often be simplified with type aliases:

A pointer to function can be used as the left-hand operand of the function call operator , this invokes the pointed-to function:

Dereferencing a function pointer yields the lvalue identifying the pointed-to function:

A pointer to function may be initialized from an overload set which may include functions, function template specializations, and function templates, if only one overload matches the type of the pointer (see address of an overloaded function for more detail):

Equality comparison operators are defined for pointers to functions (they compare equal if pointing to the same function).

[ edit ] Pointers to members

[ edit ] pointers to data members.

A pointer to non-static member object m which is a member of class C can be initialized with the expression & C :: m exactly. Expressions such as & ( C :: m ) or & m inside C 's member function do not form pointers to members.

Such a pointer may be used as the right-hand operand of the pointer-to-member access operators operator. * and operator - > * :

Pointer to data member of an accessible unambiguous non-virtual base class can be implicitly converted to pointer to the same data member of a derived class:

Conversion in the opposite direction, from a pointer to data member of a derived class to a pointer to data member of an unambiguous non-virtual base class, is allowed with static_cast and explicit cast , even if the base class does not have that member (but the most-derived class does, when the pointer is used for access):

The pointed-to type of a pointer-to-member may be a pointer-to-member itself: pointers to members can be multilevel, and can be cv-qualified differently at every level. Mixed multi-level combinations of pointers and pointers-to-members are also allowed:

[ edit ] Pointers to member functions

A pointer to non-static member function f which is a member of class C can be initialized with the expression & C :: f exactly. Expressions such as & ( C :: f ) or & f inside C 's member function do not form pointers to member functions.

Such a pointer may be used as the right-hand operand of the pointer-to-member access operators operator. * and operator - > * . The resulting expression can be used only as the left-hand operand of a function-call operator:

Pointer to member function of a base class can be implicitly converted to pointer to the same member function of a derived class:

Conversion in the opposite direction, from a pointer to member function of a derived class to a pointer to member function of an unambiguous non-virtual base class, is allowed with static_cast and explicit cast , even if the base class does not have that member function (but the most-derived class does, when the pointer is used for access):

Pointers to member functions may be used as callbacks or as function objects, often after applying std::mem_fn or std::bind :

[ edit ] Null pointers

Pointers of every type have a special value known as null pointer value of that type. A pointer whose value is null does not point to an object or a function (the behavior of dereferencing a null pointer is undefined), and compares equal to all pointers of the same type whose value is also null .

A null pointer constant can be used to initialize a pointer to null or to assign the null value to an existing pointer, it is one of the following values:

  • An integer literal with value zero.
(usually nullptr). (since C++11)

The macro NULL can also be used, it expands to an implementation-defined null pointer constant.

Zero-initialization and value-initialization also initialize pointers to their null values.

Null pointers can be used to indicate the absence of an object (e.g. std::function::target() ), or as other error condition indicators (e.g. dynamic_cast ). In general, a function that receives a pointer argument almost always needs to check if the value is null and handle that case differently (for example, the delete expression does nothing when a null pointer is passed).

[ edit ] Invalid pointers

A pointer value p is valid in the context of an evaluation e if one of the following condition is satisfied:

  • p is a null pointer value.
  • p it is a pointer to or past the end of an object o , and e is in the duration of the region of storage for o .

If a pointer value p is used in an evaluation e , and p is not valid in the context of e , then:

  • If e is an indirection or an invocation of a deallocation function , the behavior is undefined.
  • Otherwise, the behavior is implementation-defined.

[ edit ] Constness

  • If cv appears before * in the pointer declaration, it is part of the declaration specifier sequence and applies to the pointed-to object.
  • If cv appears after * in the pointer declaration, it is part of the declarator and applies to the pointer that's being declared.
Syntax meaning
const T* pointer to constant object
T const* pointer to constant object
T* const constant pointer to object
const T* const constant pointer to constant object
T const* const constant pointer to constant object

In general, implicit conversion from one multi-level pointer to another follows the rules described in qualification conversions .

[ edit ] Composite pointer type

When an operand of a comparison operator or any of the second and third operands of a conditional operator is a pointer or pointer-to-member, a composite pointer type is determined to be the common type of these operands.

Given two operands p1 and p2 having types T1 and T2 , respectively, p1 and p2 can only have a composite pointer type if any of the following conditions are satisfied:

and p2 are both pointers. and p2 is a pointer and the other operand is a null pointer constant.
and p2 are both null pointer constants, and at least one of and is a non-integral type. (since C++11)
  • At least one of T1 and T2 is a pointer type, pointer-to-member type or std::nullptr_t .

The composite pointer type C of p1 and p2 is determined as follows:

is a , is . is a null pointer constant, is . (until C++11)
and p2 are both , is . is a null pointer constant, is . is a null pointer constant, is . (since C++11)
  • Otherwise, if all following conditions are satisfied:
  • T1 or T2 is “pointer to cv1 void ”.
  • The other type is “pointer to cv2 T ”, where T is an object type or void .
or is “pointer to function type ”. ”. and are the same except noexcept. is “pointer to ”. (since C++17)
  • T1 is “pointer to C1 ”.
  • T2 is “pointer to C2 ”.
  • One of C1 and C2 is reference-related to the other.
  • the qualification-combined type of T1 and T2 , if C1 is reference-related to C2 , or
  • the qualification-combined type of T2 and T1 , if C2 is reference-related to C1 .
or is “pointer to member of of function type ”. of noexcept function type ”. and is reference-related to the other. and are the same except noexcept. is of type ”, if is reference-related to , or of type ”, if is reference-related to . (since C++17)
  • T1 is “pointer to member of C1 of non-function type M1 ”.
  • T2 is “pointer to member of C2 of non-function type M2 ”
  • M1 and M2 are the same except top-level cv-qualifications.
  • the qualification-combined type of T2 and T1 , if C1 is reference-related to C2 , or
  • the qualification-combined type of T1 and T2 , if C2 is reference-related to C1 .
  • Otherwise, if T1 and T2 are similar types , C is the qualification-combined type of T1 and T2 .
  • Otherwise, p1 and p2 do not have a composite pointer type, a program that necessitates the determination of C such a type is ill-formed.

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++98 a pointer to an object never compares equal
to a pointer to one past the end of an array
for non-null and non-function pointers,
compare the addresses they represent
C++98 any integral constant expression that
evaluates to 0 was a null pointer constant
limited to integer
literals with value 0
C++98 the behavior of using an invalid pointer
value in any way was undefined
behaviors other than indirection and
passing to deallocation functions
are implementation-defined

( )
C++98 the rule of composite pointer type was incomplete, and thus
did not allow comparison between int** and const int**
made complete
C++98 a pointer to void and a pointer to
function had a composite pointer type
they do not have such a type
C++17 function pointer conversions were not allowed
when determining the composite pointer type
allowed
C++98 reaching the end of the duration of a region
of storage could invalidate pointer values
pointer validity is based
on the evaluation context

[ edit ] See also

for Pointer declaration
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 13 June 2024, at 02:53.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • 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.

Error:Assignment makes pointer from integer without a cast

i keep getting that error in line: (p=exp[i];) Im trying to send a char array, and (i,num) integers, the 'i' im just putting it to be 0 for now, until the code works so dont give attention to it. but the function should return the place of the first character in "exp" that is not a number, with being sure that all the ones before are numbers.

Josmar's user avatar

3 Answers 3

p is a char* so you need to assign a pointer to it but exp[i] returns a single char element from an array. Try

simonc's user avatar

do correct the line to correspond to the following p=&(exp[i]); this means that you are assigning the pointer of exp[i] to p.

hmatar's user avatar

You need take the address-of instead of and then pass to p , that's a pointer. In other words,you are assign char to a char* returned from value at i index in exp` array.

Try this: p = &exp[i];

Jack's user avatar

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 .

  • The Overflow Blog
  • Masked self-attention: How LLMs learn relationships between tokens
  • Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Preventing unauthorized automated access to the network
  • Feedback Requested: How do you use the tagged questions page?

Hot Network Questions

  • Evil machine/Alien entity kills man but his consciousness/brain remains alive within it, and he spends eons reading its mind to defeat it and escape
  • How to format units inside math environment?
  • Book where a parent recounts an anecdote about a painting of a Russian sled pursued by wolves
  • Why does not Earth radiate more energy into the space while it gets warmer?
  • In the Silmarillion or the Appendices to ROTK, do the Dwarves of Khazad-dûm know about the Balrog below prior to Durin receiving the ring?
  • Why does Lebanon apparently lack aerial defenses?
  • What is the greatest possible number of empty squares that could remain after the jumps?
  • What is the average result of rolling Xd6 twice and taking the higher of the two sums?
  • In big band horn parts, should I write double flats (sharps) or the enharmonic equivalent?
  • God the Father punished the Son as sin-bearer: how does that prove God’s righteousness?
  • Are file attachments in email safe for transferring financial documents?
  • Status of infinitesimal Hilbert's sixteenth problem
  • How can I award a player an additional Feat?
  • Is mathematical Platonism possible without mind-body dualism?
  • How to enable (turn on) a 5V power rail with a 3.3V MCU power rail?
  • Incorporated dough mix into sourdough starter
  • nicematrix \midrule undefined
  • Can I possibly win in this kind of situation?
  • Is this a proof for energy conservation?
  • World's smallest Sudoku!
  • Which ancient philosopher compared thoughts to birds?
  • Does any abbreviation especially used in writing?
  • Help Understanding Op-Amp Mixing of Square Waves Swinging from 0V to 9V
  • Is it Possible to Successfully Do a PhD in the UK Without Formal University Enrolment?

pointer assignment error

IMAGES

  1. How do I fix the null pointer assignment error?

    pointer assignment error

  2. How do I fix the null pointer assignment error?

    pointer assignment error

  3. what is null pointer assignment error in c

    pointer assignment error

  4. Compiler/AM6548: Pointer assignment problem on Cortex A53 with GCC

    pointer assignment error

  5. what is null pointer assignment error in c

    pointer assignment error

  6. Solved b) What does the error 'Null Pointer Assignment mean

    pointer assignment error

VIDEO

  1. What are Pointers? How to Use Them? and How they can Improve your C++ Programming Skills

  2. 2. Declaring & Initializing Pointers in C++

  3. Extra Problems 1 Pointers double pointers tracing inside function

  4. C++ Pointers: Common Problems and How to Solve Them|| Dangling, Wild , Null Pointers|| Lecture 13

  5. #27 What is pointer in C language

  6. Mouse pointer works but not able to click on Windows 11

COMMENTS

  1. c

    A null pointer assignment error, or many other errors, can be assigned to this issue and example. In simpler architecture or programming environments, It can refer to any code which unintentionally ends up creating nulls as pointers, or creates a bug that in anyway halts the execution, like overwriting a byte in the return stack, overwriting ...

  2. How do I fix warning: assignment from incompatible pointer type?

    A pointer of type int** has to point to an object of type int*.There is no object of type int* in your program.a2d is an object of type int[2][2], consisting of two objects of type int[2], each of which consists of two objects of type int.You can derive pointer values from each of these, but there are no int* pointer objects unless you define them. - Keith Thompson

  3. c

    Here: ptr_one = &x; ptr_two = &x; ptr_three = &y; ptr_one, ptr_two and ptr_three are int*s and &x and &y are double*s.You are trying to assign an int* with a double*.Hence the warning. Fix it by changing the types of the pointers to double* instead of int*, i.e, change the following lines. int *ptr_one; int *ptr_two; int *ptr_three;

  4. Incompatible Pointer Types in C: A Guide to Fixing Errors

    char *q; p = q; // Error: incompatible pointer types. This is because the pointer `p` is of type `int *`, and the pointer `q` is of type `char *`. These two types are incompatible, and you cannot assign a pointer of one type to a variable of another type. An incompatible pointer type is a pointer that is not of the same type as the variable ...

  5. Top 20 C pointer mistakes and how to fix them

    Mistake # 11 : Creating garbage objects using C pointers. You need a pointer to a memory location to free / deallocate that memory. If you re-assign a pointer and there is no other pointer pointing to that memory block, you cannot deallocate that previous memory block. This causes a memory leak.

  6. Assignment makes integer from pointer without a cast in c

    If you read this far, tweet to the author to show them you care. Tweet a Thanks

  7. Null Pointer Assignment Errors Explained

    Technical Information Database TI500C.txt Null Pointer Assignment Errors Explained Category :General Platform :All Product :Borland C++ All Description: 1.

  8. Null Pointer Assignment Errors Explained

    Technical Information Database TI500C.txt Null Pointer Assignment Errors Explained Category :General Platform :All Product :Borland C++ All Description: 1.

  9. Pointer assignment Error

    Either change the type of the fields to std::string, or derefence the field before assigning to it. ie. myClass->field1 = &myString; Now the pointer points to myString. *myClass->field1 represents the string pointed to by field1. is that the field1 pointer will become invalid when myString goes out of scope.

  10. Clang++ pointer assignment error message

    Consider the following program void func(int n) { int i; int grp[n][n]; int (*ptr)[n]; for (i = 0; i < n; i++) grp[i][i] = i; for (i = 0; i < n; i++) ptr = &grp[i ...

  11. [SOLVED] C

    Re: C - assigment makes integer from pointer without a cast warning. path [1] is the second element of a char array, so it's a char. home is a char *, i.e. a pointer to a char. You get the warning because you try to assign a char* to a char. Note also the potential to overflow your buffer if the content of the argv [1] argument is very long.

  12. Dereferencing Pointer to Incomplete Type Error in C

    Dereferencing a Pointer in C. Dereference operations begin at the pointer and follow up to the pointee. The objective could be to examine or modify the pointee state. A pointer can only be dereferenced if it has a pointee; the pointee must also be allocated before the pointer can be made to point at it.

  13. NULL Pointer in C

    Syntax of Null Pointer Declaration in C. type pointer_name = NULL; type pointer_nam e = 0; We just have to assign the NULL value. Strictly speaking, NULL expands to an implementation-defined null pointer constant which is defined in many header files such as " stdio.h ", " stddef.h ", " stdlib.h " etc.

  14. Dangling, Void , Null and Wild Pointers in C

    A null pointer stores a defined value, but one that is defined by the environment to not be a valid address for any member or object. NULL vs Void Pointer - Null pointer is a value, while void pointer is a type. Wild pointer in C. A pointer that has not been initialized to anything (not even NULL) is known as a wild pointer. The pointer may ...

  15. C Warning

    Solution 1. You only have a const void* and assign that to a void*. Hence you can modify the target with pt_SAP->pt_param although you could not with pt_Param. This breaks the contract of the function parameter declaration, which "promises" not to modify the object to which pt_Param pointer. And hence the warning. Nice explanation, 5ed.

  16. I keep getting an error: incompatible pointer types passing 'string

    This would help you resolve that particular error, but there are bigger issues that will likely make this a moot point. In reading your code, it's not clear what you were trying to do. Part of it looks like it is trying to cycle through the key string to 'shift' all of it's elements.

  17. C

    The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double-pointers. We can use a pointer to a pointer to change the values of normal pointers or create a variable-sized 2-D array.

  18. c

    6.7.6.1 Pointer declarators. 2 For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types. However types int or char on the one hand and type void on the other hand are not compatible types. You could define your functions the following way

  19. C Pointers

    datatype ** pointer_name; Dereferencing Double Pointer *pointer_name; // get the address stored in the inner level pointer **pointer_name; // get the value pointed by inner level pointer. Note: In C, we can create multi-level pointers with any number of levels such as - ***ptr3, ****ptr4, *****ptr5 and so on. 6. NULL Pointer. The Null Pointers are those pointers that do not point to any ...

  20. Pointer declaration

    If the original pointer is pointing to a base class subobject within an object of some polymorphic type, dynamic_cast may be used to obtain a void * that is pointing at the complete object of the most derived type. Pointers to void have the same size, representation and alignment as pointers to char.. Pointers to void are used to pass objects of unknown type, which is common in C interfaces ...

  21. Error:Assignment makes pointer from integer without a cast

    You need take the address-of instead of and then pass to p, that's a pointer. In other words,you are assign char to a char* returned from value at i index in exp` array. Try this: p = &exp[i]; answered Jan 9, 2013 at 19:13. Jack.