-1

Can anyone help converting the Int to char array as i have buffer as

char *buffer = NULL;  
int lengthOfComponent = -1;   
char *obj;
buffer[index]= (char *)&lengthOfComponent; 

if i do this it is thorwing EXCESS BAD ACCESS after the execution how to store the value of the obj to buffer using memcpy

Mahesh
  • 34,573
  • 20
  • 89
  • 115
012346
  • 199
  • 1
  • 4
  • 23

2 Answers2

2

Of course you cannot write in buffer[index], it is not allocated!

buffer = malloc(sizeof(char) * lengthOfBuffer);

should do it. After that you can write the buffer with memcpy or with an assignation, like you are doing.

Jorge Aguirre
  • 2,787
  • 3
  • 20
  • 27
0
buffer[index] = (char *)&lengthOfComponent;

buffer[index] is like dereferencing the pointer. But buffer is not pointing to any valid location. Hence the runtime error.

The C solution is using snprintf. Try -

int i = 11;
char buffer[10];

snprintf(buffer, sizeof(buffer), "%d", i);
Mahesh
  • 34,573
  • 20
  • 89
  • 115
  • `Incompatible pointer to integer conversion assigning to 'char' from 'char *'; dereference with *` it is throwing this warning – 012346 Jul 23 '12 at 12:47
  • It is exactly what is mentioned in the answer. `buffer[index]` gives the character at the index location but not the pointer. The question is why do you want a character pointer to point to an integer location. – Mahesh Jul 23 '12 at 12:49
  • basically i want the length of component value to store in the buffer[index] please help me out doing this – 012346 Jul 23 '12 at 12:53