开发者

C pointers. Assignement of large numbers to char * pointers

#include "stdio.h"
#include "malloc.h"

int main()

{

  开发者_开发百科  char*x=(char*)malloc(1024);
    *(x+2)=3; -----------------------------> Problem with big numbers 
    printf("\n%d",*(x+2));
    printf("\n%d",sizeof(long int));
    printf("\n %ld \n\n",(long int)sizeof(long int));
}

This works fine when I give small numbers in the line marked with an arrow (------->), but does not work for large values. I want to store big numbers. What should I do?


You are allocating a char buffer. The elements of such an array is only guaranteed to hold small values, at most up to 255. If you want to store numeric values, use some numeric array instead (e.g. long or int, depending on how large the desired values actually are). E.g.

long* x = (long*)malloc(1024 * sizeof(long));
x[2] = 319222; // x[2] is equivalent to *(x+2)

Here you can check the limits for all scalar data types in C.


Use a larger type, like an int or a long. In C, char is usually only an 8 bit quantity which will be limited to a valid range of +/- 128.


All the buffer allocation and pointer arithmetic is getting in the way of understanding. Essentially the issue is that char has a limited range, typically -127 to 128 or 0 to 255.

The simplest way to see your problem is with code like this:

char c = 256;//no good
int i = 256;//no problem

From what you have said in the comments, it sounds like you want to cast the char* to int* and write over the buffer that way. I hope you know what you are doing.

*(int*)x[2] = 666;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜