Convert Int to Char Array - c++

I need to make a class called MyInt which handles any size positive numbers by creating an int array. I am making a constructor to be used in converting an int (any size supported by ints) into a MyInt. I need to convert the int into a char array and then read digit by digit into the int array. So my question is, without using any libraries except <iostream> <iomanip> and <cstring> how can I convert an int with multiple digits into a character array?

You don't need to make a char array as an intermediary step. The digits (I assume in base 10) can be obtained one by one using modulo 10 operations. Something like:
convert(int *ar, const int i)
{
int p, tmp;
tmp = i
while (tmp != 0)
{
ar[p] = tmp % 10;
tmp = (tmp - ar[p])/10;
p++;
}
}

Not sure if this is what you want, but:
int myInt = 30;
char *chars = reinterpret_cast<char*>(&myInt);
And you can get the 4 separate char's:
chars[0]; // is the first char
chars[1]; // is the second char
chars[2]; // is the third char, and
chars[3]; // is the fourth/last char
...but I'm not entirely sure if that's what you are looking for.

One possible way of doing that conversion with such restraints is as follows:
function convert:
//find out length of integer (integer division works well)
//make a char array of a big enough size (including the \0 if you need to print it)
//use division and modulus to fill in the array one character at a time
//if you want readable characters, don't forget to adjust for them
//don't forget to set the null character if you need it
I hope I didn't misunderstand your question, but that worked for me, giving me a printable array that read the same as the integer itself.

Related

Multiply 2 1000-digit binary numbers in C++ [duplicate]

I have the following code
int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;
When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?
The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.
As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?
Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.
For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial
Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.
ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.
You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.
First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).
I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}
Use float instead. It can go up to about 3.4028235 × 1038
// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}
You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

Why does my array element retrieval function return random value?

I am trying to make an own simple string implementation in C++. My implementation is not \0 delimited, but uses the first element in my character array (the data structure I have chosen to implement the string) as the length of the string.
In essence, I have this as my data structure: typedef char * arrayString; and I have got the following as the implementation of some primal string manipulating routines:
#include "stdafx.h"
#include <iostream>
#include "new_string.h"
// Our string implementation will store the
// length of the string in the first byte of
// the string.
int getLength(const arrayString &s1) {
return s1[0] - '0';
}
void append_str(arrayString &s, char c) {
int length = getLength(s); // get the length of our current string
length++; // account for the new character
arrayString newString = new char[length]; // create a new heap allocated string
newString[0] = length;
// fill the string with the old contents
for (int counter = 1; counter < length; counter++) {
newString[counter] = s[counter];
}
// append the new character
newString[length - 1] = c;
delete[] s; // prevent a memory leak
s = newString;
}
void display(const arrayString &s1) {
int max = getLength(s1);
for (int counter = 1; counter <= max; counter++) {
std::cout << s1[counter];
}
}
void appendTest() {
arrayString a = new char[5];
a[0] = '5'; a[1] = 'f'; a[2] = 'o'; a[3] = 't'; a[4] = 'i';
append_str(a, 's');
display(a);
}
My issue is with the implementation of my function getLength(). I have tried to debug my program inside Visual Studio, and all seems nice and well in the beginning.
The first time getLength() is called, inside the append_str() function, it returns the correct value for the string length (5). When it get's called inside the display(), my own custom string displaying function (to prevent a bug with std::cout), it reads the value (6) correctly, but returns -42? What's going on?
NOTES
Ignore my comments in the code. It's purely educational and it's just me trying to see what level of commenting improves the code and what level reduces its quality.
In get_length(), I had to do first_element - '0' because otherwise, the function would return the ascii value of the arithmetic value inside. For instance, for decimal 6, it returned 54.
This is an educational endeavour, so if you see anything else worth commenting on, or fixing, by all means, let me know.
Since you are getting the length as return s1[0] - '0'; in getLength() you should set then length as newString[0] = length + '0'; instead of newString[0] = length;
As a side why are you storing the size of the string in the array? why not have some sort of integer member that you store the size in. A couple of bytes really isn't going to hurt and now you have a string that can be more than 256 characters long.
You are accessing your array out of bounds at couple of places.
In append_str
for (int counter = 1; counter < length; counter++) {
newString[counter] = s[counter];
}
In the example you presented, the starting string is "5foti" -- without the terminating null character. The maximum valid index is 4. In the above function, length has already been set to 6 and you are accessing s[5].
This can be fixed by changing the conditional in the for statement to counter < length-1;
And in display.
int max = getLength(s1);
for (int counter = 1; counter <= max; counter++) {
std::cout << s1[counter];
}
Here again, you are accessing the array out of bounds by using counter <= max in the loop.
This can be fixed by changing the conditional in the for statement to counter < max;
Here are some improvements, that should also cover your question:
Instead of a typedef, define a class for your string. The class should have an int for the length and a char* for the string data itself.
Use operator overloads in your class "string" so you can append them with + etc.
The - '0' gives me pain. You subtract the ASCII value of 42 from the length, but you do not add it as a character. Also, the length can be 127 at maximum, because char goes from -128 to +127. See point #1.
append_str changes the pointer of your object. That's very bad practice!
Ok, thank you everyone for helping me out.
The problem appeared to be inside the appendTest() function, where I was storing in the first element of the array the character code for the value I wanted to have as a size (i.e storing '5' instead of just 5). It seems that I didn't edit previous code that I had correctly, and that's what caused me the issues.
As an aside to what many of you are asking, why am I not using classes or better design, it's because I want to implement a basic string structure having many constraints, such as no classes, etc. I basically want to use only arrays, and the most I am affording myself is to make them dynamically allocated, i.e resizable.

go equivalents of c types

What are the right equivalent of unsigned char or unsigned char* in go? Or am I even doing this right?
I have this C++ class:
class ArcfourPRNG
{
public:
ArcfourPRNG();
void SetKey(unsigned char *pucKeyData, int iKeyLen);
void Reset();
unsigned char Rand();
private:
bool m_bInit;
unsigned char m_aucState0[256];
unsigned char m_aucState[256];
unsigned char m_ucI;
unsigned char m_ucJ;
unsigned char* m_pucState1;
unsigned char* m_pucState2;
unsigned char m_ucTemp;
};
I am trying to rewrite it to go:
type ArcfourPRNG struct {
m_bInit bool
m_aucState0 [256]byte
m_aucState [256]byte
m_ucI, m_ucJ []byte
*m_pucState1 []byte
*m_pucState2 []byte
m_ucTemp []byte
}
func (arc4 *ArcfourPRNG) SetKey(pucKeyData []byte, iKeyLen int) {
func (arc4 *ArcfourPRNG) Reset() {
func (arc4 *ArcfourPRNG) Rand() uint {
Well, I just started with go a few hours ago. So this is still confusing me.
A function
for(i=0; i<256; i++)
{
m_pucState1 = m_aucState0 + i;
m_ucJ += *m_pucState1 + *(pucKeyData+m_ucI);
m_pucState2 = m_aucState0 + m_ucJ;
//Swaping
m_ucTemp = *m_pucState1;
*m_pucState1 = *m_pucState2;
*m_pucState2 = m_ucTemp;
m_ucI = (m_ucI + 1) % iKeyLen;
}
memcpy(m_aucState, m_aucState0, 256); // copy(aucState[:], aucState0) ?
Hopefully this can clear a few things up for you.
For storing raw sequences of bytes, use a slice []byte. If you know exactly how long the sequence will be, you can specify that, e.g. [256]byte but you cannot resize it later.
While Go has pointers, it does not have pointer arithmetic. So you will need to use integers to index into your slices of bytes.
For storing single bytes, byte is sufficient; you don't want a slice of bytes. Where there are pointers in the C++ code used to point to specific locations in the array, you'll simply have an integer index value that selects one element of a slice.
Go strings are not simply sequences of bytes, they are sequences of UTF-8 characters stored internally as runes, which may have different lengths. So don't try to use strings for this algorithm.
To reimplement the algorithm shown, you do not need either pointers or pointer arithmetic at all. Instead of keeping pointers into the byte arrays as you would in C++, you'll use int indexes into the slices.
This is kind of hard to follow since it's virtually all pointer arithmetic. I would want to have a description of the algorithm handy while converting this (and since this is probably a well-known algorithm, that should not be hard to find). I'm not going to do the entire conversion for you, but I'll demonstrate with hopefully a simpler example. This prints each character of a string on a separate line.
C++:
unsigned char *data = "Hello World";
unsigned char *ptr = 0;
for (int i = 0; i < std::strlen(data); i++) {
ptr = i + data;
std::cout << *ptr << std::endl;
}
Go:
data := []byte("Hello World")
for i := 0; i < len(data); i++ {
// The pointer is redundant already
fmt.Println(data[i:i+1])
}
So, learn about Go slices, and when you do reimplement this algorithm you will likely find the code to be somewhat simpler, or at least easier to understand, than its C++ counterpart.

How can I multiply really big numbers c++

I have the following code
int i, a, z;
i = 2343243443;
a = 5464354324324324;
z = i * a;
cout << z << endl;
When these are multiplied it gives me -1431223188 which is not the answer. How can I make it give me the correct answer?
The result overflows the int (and also std::uint64_t)
You have to use some BigInt library.
As Jarod42 suggested is perfectly okay, but i am not sure whether overflow will take place or not ?
Try to store each and every digit of number in an array and after that multiply. You will definitely get the correct answer.
For more detail how to multiply using array follow this post http://discuss.codechef.com/questions/7349/computing-factorials-of-a-huge-number-in-cc-a-tutorial
Use pan paper approach as we used in 2nd standard.
Store two numbers in two different array in reverse order. And take ans array as size of (arr1.size + arr2.size).And also initilize ans array to zero.
In your case
arr1[10]={3,4,4,3,4,2,3,4,3,2},
arr2[15]={4,2,3,4,2,3,,4,5,3,4,5,3,4,6,4,5};
for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{
ans[i+j]+=arr1[i]*arr2[j];
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
Then ans array contain the result.Please print carefully ans array. it may contain leading zero.
ints only hold 32 bits. When the result of a multiplication is larger than 2^31 - 1, the result rolls over to a large negative value. Instead of using the int data type, use long long int, which holds 64 bits.
You should first try to use 64-bit numbers (long or better, unsigned long if everything is positive). With unsigned long you can operate between 0 and 18446744073709551615, with long between -9223372036854775808 and 9223372036854775807.
If it is not enough, then there is no easy solution, you have to perform your operation at software level using arrays of unsigned long for instance, and overload "<<" operator for display. But this is not that easy, and I guess you are a beginner (no offense) considering the question you asked.
If 64-bit representation is not enough for you, I think you should consider floating-point representation, especially "double". With double, you can represent numbers between about -10^308 and 10^308. You won't be able to have perfectly accurate computatiosn on very large number (the least significant digits won't be computed), but this should be a good-enough option for whatever you want to do here.
First, you have to make your value long longs
Second, you would want to add a (long long) in front of the multiplication. This is because when you have (ab) it returns an int therefore if you want it to return a long long you would want (long long)(ab).
I would like to elaborate on, and clarify Shravan Kumar's Answer using a full-fledged code. The code starts with a long integers a & b, which are multiplied using array, converted to a string and then back into the long int.
#include <iostream>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
//Numbers to be multiplied
long a=111,b=100;
//Convert them to strings (or character array)
string arr1 = to_string(a), arr2 = to_string(b);
//Reverse them
reverse(arr1.begin(), arr1.end());
reverse(arr2.begin(), arr2.end());
//Getting size for final result, just to avoid dynamic size
int ans_size = arr1.size() + arr2.size();
//Declaring array to store final result
int ans[ans_size]={0};
//Multiplying
//In a reverse manner, just to avoid reversing strings explicitly
for(int i=0; i<arr1.size();i++)
{
for(int j=0; j<arr2.size();j++)
{
//Convert array elements (char -> int)
int p = (int)(arr1[i]) - '0';
int q = (int)(arr2[j]) - '0';
//Excerpt from Shravan's answer above
ans[i+j]+=p*q;
ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
ans[i+j]%=10;
}
}
//Declare array to store string form of final answer
string s="";
for(auto i=0;i<ans_size; ++i)
s += to_string(ans[i]);
reverse(s.begin(), s.end() );
//If last element is 0, it should be skipped
if(s[0] =='0')
{
string ss(s,1,s.size()-1);
s=ss;
}
//Final answer
cout<< s;
return 0;
}
Use float instead. It can go up to about 3.4028235 × 1038
// its may heplfull for you
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAX 1000
void reverse(char *from, char *to ){
int len=strlen(from);
int l;
for(l=0;l<len;l++)to[l]=from[len-l-1];
to[len]='\0';
}
void call_mult(char *first,char *sec,char *result){
char F[MAX],S[MAX],temp[MAX];
int f_len,s_len,f,s,r,t_len,hold,res;
f_len=strlen(first);
s_len=strlen(sec);
reverse(first,F);
reverse(sec,S);
t_len=f_len+s_len;
r=-1;
for(f=0;f<=t_len;f++)temp[f]='0';
temp[f]='\0';
for(s=0;s<s_len;s++){
hold=0;
for(f=0;f<f_len;f++){
res=(F[f]-'0')*(S[s]-'0') + hold+(temp[f+s]-'0');
temp[f+s]=res%10+'0';
hold=res/10;
if(f+s>r) r=f+s;
}
while(hold!=0){
res=hold+temp[f+s]-'0';
hold=res/10;
temp[f+s]=res%10+'0';
if(r<f+s) r=f+s;
f++;
}
}
for(;r>0 && temp[r]=='0';r--);
temp[r+1]='\0';
reverse(temp,result);
}
int main(){
char fir[MAX],sec[MAX],res[MAX];
while(scanf("%s%s",&fir,&sec)==2){
call_mult(fir,sec,res);
int len=strlen(res);
for(int i=0;i<len;i++)printf("%c",res[i]);
printf("\n");
}
return 0;
}
You can use queue data structure to find the product of two really big numbers with O(n*m). n and m are the number of digits in a number.

Using pointer for crossing over all elements in INTEGER array

Is there a way to cross over all elements in integer array using pointer ( similiar to using pointer to cross over string elements).I know that integer array is not NULL terminated so when I try to cross over array using pointer it overflows.So I added NULL as a last element of an array and it worked just fine.
int array[7]={1,12,41,45,58,68,NULL};
int *i;
for(i=array;*i;i++)
printf("%d ",*i);
But what if one of the elements in array is 0 ,that will behave just as NULL.Is there any other way that will implement pointer in crossing over all elements in integer array?
In general, no unless you pick a sentinel value that's not part of the valid range of the data. For example, the valid range might be positive numbers, so you can use a negative number like -1 as a sentinel value that indicates the end of the array. This how C-style strings work; the NULL terminator is used because it's outside of the valid range of integers that could represent a character.
However, it's usually better to somehow pair up the array pointer with another variable that indicates the size of the array, or another pointer that points one-past-the-end of the array.
In your specific case, you can do something like this:
// Note that you don't have to specify the length of the array.
int array[] = {1,12,41,45,58,68};
// Let the compiler count the number of elements for us.
int arraySize = sizeof(array)/sizeof(int);
// or int arraySize = sizeof(array)/sizeof(array[0]);
int main()
{
int* i;
for(i = array; i != array + arraySize; i++)
printf("%d ",*i);
}
You can also do this:
int arrayBegin[] = {1,12,41,45,58,68};
int* arrayEnd = arrayBegin + sizeof(arrayBegin)/sizeof(arrayBegin[0]);
int main()
{
int* i;
for(i = arrayBegin; i != arrayEnd; i++)
printf("%d ",*i);
}
But given only a pointer, no you can't know how long the array it points to is. In fact, you can't even tell if the pointer points to an array or a single object! (At least not portably.)
If you have functions that must accept an array, either have your function require:
the pointer and the size of the array pointed by the pointer,
or two pointers with one pointing to the first element of the array and one pointing one-past-the-end of the array.
I'd like to give some additional advice: Never use some kind of sentinel/termination value in arrays for determining their bounds. This makes your programs prone to error and is often the cause for security issues. You should always store the length of arrays to limit all operations to their bounds and test against that value.
In C++ you have the STL and its containers.
In C you'll effectively end up using structures like
typedef struct t_int_array
{
size_t length;
int data[1]; /* note the 1 (one) */
} int_array;
and a set of manipulation functions like this
int_array * new_int_array(size_t length)
{
int_array * array;
/* we're allocating the size of basic t_int_array
(which already contains space for one int)
and additional space for length-1 ints */
array = malloc( sizeof(t_int_array) + sizeof(int) * (length - 1) );
if(!array)
return 0;
array->length = length;
return array;
}
int_array * concat_int_arrays(int_array const * const A, int_array const * const B);
int_array * int_array_push_back(int_array const * const A, int const value);
/* and so on */
This method will make the compiler align the t_int_array struct in a way, that it's optimal for the targeted architecture (also with malloc allocation), and just allocating more space in quantities of element sizes of the data array element will keep it that way.
The reason that you can iterate across a C-style string using pointers is that of the 256 different character values, one has been specifically reserved to be interpreted as "this is the end of the string." Because of this, C-style strings can't store null characters anywhere in them.
When you're trying to use a similar trick for integer arrays, you're noticing the same problem. If you want to be able to stop at some point, you'll have to pick some integer and reserve it to mean "this is not an integer; it's really the end of the sequence of integers." So no, there is no general way to take an array of integers and demarcate the end by a special value unless you're willing to pick some value that can't normally appear in the string.
C++ opted for a different approach than C to delineate sequences. Instead of storing the elements with some sort of null terminator, C++-style ranges (like you'd find in a vector, string, or list) store two iterators, begin() and end(), that indicate the first element and first element past the end. You can iterate over these ranges by writing
for (iterator itr = begin; itr != end; ++itr)
/* ... visit *itr here ... */
This approach is much more flexible than the C-string approach to defining ranges as it doesn't rely on specific properties of any values in the range. I would suggest opting to use something like this if you want to iterate over a range of integer values. It's more explicit about the bounds of the range and doesn't run into weird issues where certain values can't be stored in the range.
Apart from the usual suggestion that you should go and use the STL, you can find the length of a fixed array like this:
int array[6]={1,12,41,45,58,68};
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{ }
If you use a templated function, you can implicitly derive the length like this:
template<size_t len> void func(int (&array)[len])
{
for (int i = 0; i < len; ++i) { }
}
int array[6]={1,12,41,45,58,68};
func(array);
If 0 is a value that may occur in a normal array of integers, you can specify a different value:
const int END_OF_ARRAY = 0x80000000;
int array[8]={0,1,12,41,45,58,68,END_OF_ARRAY};
for (int i = 0; array[i] != END_OF_ARRAY; ++i)
{ }
If every value is a possibility, or if none of the other approaches will work (for example, a dynamic array) then you have to manage the length separately. This is how strings that allow embedded null characters work (such as BSTR).
In your example you are using (or rather abusing) the NULL macro as a sentinel value; this is the function of the NUL('\0') character in a C string, but in the case of a C string NUL is not a valid character anywhere other than as the terminal (or sentinel) value .
The NULL macro is intended to represent an invalid pointer not an integer value (although in C++ when implicitly or explicitly cast to an int, its value is guaranteed to be zero, and in C this is also almost invariably the case). In this case if you want to use zero as the sentinel value you should use a literal zero not NULL. The problem is of course that if in this application zero is a valid data value it is not suitable for use as a sentinel.
So for example the following might suit:
static const int SENTINEL_VALUE = -1 ;
int array[7] = { 1, 12, 41, 45, 58, 68, SENTINEL_VALUE } ;
int* i ;
for( i = array; *i != SENTINEL_VALUE; i++ )
{
printf( "%d ", *i ) ;
}
If all integer values are are valid data values then you will not be able to use a sentinel value at all, and will have to use either a container class (which knows its length) or iterate for the known length of the array (from sizeof()).
Just to pedanticize and expand a little on a previous answer: in dealing with integer arrays in C, it's vanishingly rare to rely on a sentinel value in the array itself. No(1) sane programmer does that. Why not? Because by definition an integer can hold any value within predefined negative/positive limits, or (for the nowadays-not-unusual 32-bit integer) 0 to 0xffffff. It's not a good thing to redefine the notion of "integer" by stealing one of its possible values for a sentinel.
Instead, one always(1) must(1) rely on a controlling up-to-date count of integers that are in the array. Suppose we are to write a C function
that returns an int pointer to the first array member whose value is greater than the function's argument or, if there's no such member, returns NULL (all code is untested):`
int my_int_array[10]; // maximum of 10 integers in my_int_array[], which must be static
int member_count = 0; // varies from 0 to 10, always holds number of ints in my_int_array[]
int *
first_greater_than ( int val ) {
int i;
int *p;
for ( i = 0, p = my_int_array; i < member_count; ++i, ++p ) {
if ( *p > val ) {
return p;
}
}
return NULL;
}
Even better is also to limit the value of i to never count past the last possible member of my_int_array[], i.e., it never gets bigger than 9, and p never points at my_int_array[10] and beyond:
int my_int_array[10]; // maximum of 10 integers in my_int_array[], which must be static
int member_count = 0; // varies from 0 to 10, always holds number of ints in my_int_array[]
int *
first_greater_than ( int val ) {
#define MAX_COUNT sizeof(my_int_array)/sizeof(int)
int i;
int* p;
for ( i = 0, p = my_int_array; i < member_count && i < MAX_COUNT; ++i, ++p ) {
if ( *p > val ) {
return p;
}
}
return NULL;
}
HTH and I apologize if this is just too, too elementary.
--pete
Not strictly true but believe it for now
In ANSI C it's very easy and shorter than solution before:
int array[]={1,12,41,45,58,68}, *i=array;
size_t numelems = sizeof array/sizeof*array;
while( numelems-- )
printf("%d ",*i++);
Another way is to manage array of pointers to int:
#include <stdlib.h>
#include <stdio.h>
#define MAX_ELEMENTS 10
int main() {
int * array[MAX_ELEMENTS];
int ** i;
int k;
// initialize MAX_ELEMENTS,1 matrix
for (k=0;k<MAX_ELEMENTS;k++) {
array[k] = malloc(sizeof(int*));
// last element of array will be NULL pointer
if (k==MAX_ELEMENTS-1)
array[k] = NULL;
else
array[k][0] = k;
}
// now loop until you get NULL pointer
for (i=array;*i;i++) {
printf("value %i\n",**i);
}
// free memory
for (k=0;k<MAX_ELEMENTS;k++) {
free(array[k]);
}
return 0;
}
In this way loop condition is totally independent from the values of integers. But... for this to work you must use 2D array (matrix) instead of ordinary 1D array. Hope that helps.