简体   繁体   中英

manipulating what the pointer is pointing at

This is probably a really easy question but I can not seem to find an explicit answer online. Say a had a pointer to an array declared as:

static char newMessage[400]; char *p = &newMessage;

(I don't know if this is right) How would I go about manipulation the newMessage array using only the pointer. I am doing this because a C cannot return an array but can return a pointer to an array. please be gentle, I'm new

Your code is almost right; the only problem is that you have mismatched pointer types. You want:

char *p = newMessage;

Not:

char *p = &newMessage;

The latter tries to initialize p , a char * variable, with a value of type char (*)[400] , which isn't valid C.

After you've created and initialized p , you can just use it however you'd like:

p[6] = 12;

Or something like that.

Just point the pointer to the array

char* p = newMessage ;

And return it from a function.

You use it the same as you would use the array it points to.

newMessage[2] = '\0'
p[2] = '\0'

When you declare an array like static char newMessage[400] , the identifier newMessage is substituted by the address of the first element of the array, and it behaves like a pointer.

char* p= newMessage;
char* q= "Hi, world";
newMessage[4]= 'x';
p[4]= 'x';
*(newMessage + 2)= 0;
*(p+2)= 0;
strlen(newMessage);
strlen(q);
strcmp(newMessage, "Hi world");
strcmp(p, q);

are all valid expressions.

Note that in the last four function calls, you are not passing arrays, but pointers to the first character of the string. And by convention, the functions scan the memory until they find a null byte terminator.

Actually, it should be char *p = newMessage; .The char[] behaves similar to char* . You'll later modify it by how you usually modify any pointer. BTW, this is very basic so it's better you read a tutorial. Also, since you asked this, if you're planning to return a pointer to the array, the array better not be allocated on the stack. It should be heap-allocated (it's in your case since static)

You cannot actually manipulate the array, as arrays are no first class type in c.

Almost anything you care to do with the array name, will make it degenerate to a pointer. The exception being sizeof , so you can get the element count using sizeof array/sizeof *array .

What you can do, is change the values of the array elements. Use pointer arithmetic and dereferencing * . The index operator a[b] is syntactic sugar for *(a+b) .

Also, you can use library functions (or your own), which accept pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM