0

I want to ask that is there a way through which I can convert some part of int array to int variable

for example

   // my integer array contain 3,4,5,2,7 
    int array[] = {3,4,5 ,7,1,5,5,} ;

and i want a variable int to contain only first 3 member of array that is my variable should be like this

`

int var = 345 ; // first three array members

i am using c programming thanks

3 Answers 3

2

Something like this maybe ?

int var = 0;

for (i = 0; i < 3; i++) {
    var *= 10;
    var += array[i];
}
Sign up to request clarification or add additional context in comments.

Comments

0

You mean string connect?

char tmp[64];
sprintf(tmp, "%d%d%d", array[0], array[1], array[2]);
var = atoi(tmp);

Note the code above didn't check for int or buffer overflow.

Comments

-1
char *s = (char*)malloc(sizeof(char) * numOfArrayElementsToConvert);
for(int i =0;i<numOfArrayElementsToConvert;i++){
   s[i] = itoa(arr[i]);
}

int var = atoi(s);

1 Comment

itoa is not a standard c lib function and it returns char *, you use char *s without initialized.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.