I implemented a function mem_set that first allocates a memory area with malloc and then assigns v to the first n bytes of the object pointed to by the pointer p.
Then I wrote the following code to check the result.
for (int i = 0;i<n;i ++) {
cout<<"xp ["<<i<<"] ="<<xp + i<<","<<* (xp + i)<<endl;
}
Error
warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
'void *' is not a pointer-to-object type
The first warning is for xp + i and the second error is for: (xp + i).
What is a pointer to an object?
Is a general pointer like void * handled differently than a pointer like int *?
# include<iostream>
#include<cstdlib>
using namespace std;
void mem_set (void * p, int n, unsigned char v) {
unsigned char * cp = (unsigned char *) p;
while (n--) * cp ++ = v;
}
int main () {
int n;
cout<<"total index:";cin >>n;
void * xp = malloc (sizeof (char) * n);
mem_set (xp, n, 0);
for (int i = 0;i<n;i ++) {
cout<<"xp ["<<i<<"] ="<<xp + i<<","<<* (xp + i)<<endl;
}
}
-
Answer # 1
-
Answer # 2
Nachchara * Adding int value: i to xp (xp + i) increases xp by sizeof (Nachara) The
void * xp, that is, if the above "Nachara" is void
Int value: When i is added (xp + i), xp increases by sizeof (void).However, since void is a "nothing" type, sizeof (void) has no meaning and will cause an error.
'void *' is not a pointer-to-object type
Because "void * is not a pointer to Nani", * (xp + i) has no meaning.
Related articles
- file input/output is not correct
- in this case not sure why the strcmp();function works?
- about clock_t type
- Why not use async void
- typescript - type 'function' is not assignable to type
- c code does not compile with vscode
- not applicable to the type specified in java
- c - about the meaning of ((void (*)())buf)();
- c heap sort does not sort first
- c - "variables that are not used" appear for the variables that are used
- change int type to char type
- gcc does not enable ssp
- about typescript void type
- c - toupper does not work well
- c - explain why (x = y) = 5 is not good with the idea of lvalues
- c language compilation does not pass
- c - printf is not displayed
- c - sometimes heapsort does not sort well
- output does not work correctly
- scanf () does not work
void * has no target size, cast it to the required type (e.g. unsigned char *) and use it.
[Appendix] ... Is it the intended result?