I have a 13x13 array with elements but not every element is number. If its not a number, then its filled with blank space so I am trying to figure out how to check to see if a number exists at a given index. If a number exists, it does a job if not, it goes back to the loop. This is what I have:
int *spaceCheck;
int i, Value;
for(i=0;i<169;i++){
spaceCheck = &Array[i];
if(!spaceCheck){
continue;
else
//do this job
}
Can I do this? Is there any other better way to check? Thank you for you help.
Its an array of integers of 169 elements. So when the data(numbers) is initially loaded, there are only 80 elements loaded from the file into the array. The rest of the space in the array is filled with blank space (printf(" ")). Sorry for the confusion.
To do what you are asking, you need to use a sentinel value that indicates "no value", eg:
const int novalue = -1; // or whatever you want, as long as it is unique
int Array[169];
for (i=0;i<169;i++)
Array[i] = novalue;
...
for(i=0;i<169;i++){
Value = Array[i];
if(Value == novalue)
continue;
//do this job
}
Otherwise, create an array on structs instead of ints:
struct sValue
{
char valid;
int value;
};
sValue Array[169];
for (i=0;i<169;i++)
Array[i].valid = 0;
...
for(i=0;i<169;i++){
if(Array[i].valid == 0)
continue;
Value = Array[i].value;
//do this job
}
The array elements may not be initialized with zero always. The first thing you need to do is initialize it with a default value. say 0 or -1 or whatever. Then you can modify your code as follows:
int *spaceCheck;
int i, Value;
for(i=0;i<169;i++){
spaceCheck = &Array[i];
if(*spaceCheck!=default_value){
continue;
else
//do this job
}
Note that you were also storing the reference of the array element. If you want to check its data you need to use the dereferencing operator *. Hope that this is what you want. Simpler way to write the above code is to not use pointers at all. It is as follows:
int i, Value;
for(i=0;i<169;i++){
if(Array[i]!=default_value){
continue;
else
//do this job
}
I think here in this statement :if(!spaceCheck) you are checking the address of the variable to be true and you are not comparing it with any value.As for example ,if((*spacecheck)!=Array[i][j])//considering you have a 2-D array)will be logically correct as per your question.Well the following code may clear your concept,it is based on conditions similar to what you have provided here,
int *spaceCheck;
int i,j, Value;
for(i=0;i<13;i++){
for(j=0;j<13;j++){
spaceCheck=&array[i][j];//array is 2-D
if(*spaceCheck!=array[i][j])
continue;
else
//do this job
}}
Related
I am trying to solve the following problem:
Assume we have a 8 times 8 grid (of course it could be a larger grid).
We label all outer boundary points of the square as 'n', and points adjacent to them as 't', and all other points are 'f'.
I want to program a process that transfers all points to be 'n' by the following rule (I need to follow this rule, because this problem is a part of a bigger problem while the rest part is irrelevant to my question here):
I need to put all 't' points in order, and transfer the first element to be 'n'. Then I need to delete the first element which has been changed to 'n', and move the last element to the first location. Also, I need to relabel all 'f' points that are adjacent to the changed point as 't' and put them to the end of the sequence of 't' points. I need to continue this process until there is no 't' or 'f'.
To do this I used array with variable size, and my code is as the following:
int i,j;
char c[n+1][n+1];
int count=0;
int newi[4];
int newj[4];
int ind;
//initialization
for(i=0; i<n+1;i++){
for(j=0;j<n+1;j++){
if(i==0||j==0||i==n||j==n){
c[i][j]='n'; //tagged as newly known
}
else if(i==1||j==1||i==n-1||j==n-1){
c[i][j]='t'; //trial points
}
else{
c[i][j]='f'; //far away points
}
}
}
for(i=0; i<n+1;i++){
for(j=0;j<n+1;j++){
if(c[i][j]=='t'){
count=count+1; //count is number of 't'
}
}
}
int ri[count]; //array that stores the row index of trial points;
int ci[count]; //array that stores the column index of trial points;
int k=0;
for(i=0; i<n+1;i++){
for(j=0;j<n+1;j++){
if(c[i][j]=='t'){
ri[k]=i;
ci[k]=j;
k=k+1;
}
}
}
while(count>0){
int num=0;
i=ri[0];
j=ci[0];
c[i][j]='n';
ri[0]=ri[count-1];
ci[0]=ci[count-1];
count--;
int newcount=0;
if(c[i-1][j]=='f'){
c[i-1][j]='t';
newcount++;
newi[newcount-1]=i-1;
newj[newcount-1]=j;
}
if(c[i+1][j]=='f'){
c[i+1][j]='t';
newcount++;
newi[newcount-1]=i+1;
newj[newcount-1]=j;
}
if(c[i][j-1]=='f'){
c[i][j-1]='t';
newcount++;
newi[newcount-1]=i;
newj[newcount-1]=j-1;
}
if(c[i][j+1]=='f'){
c[i][j+1]='t';
newcount++;
newi[newcount-1]=i;
newj[newcount-1]=j+1;
}
count=count+newcount;
for(ind=count-newcount;ind<count;ind++)/////
{
ri[ind]=newi[ind-count+newcount];
ci[ind]=newj[ind-count+newcount];
}
}
It works fine for several loops at the beginning. However, after my careful check, then in a loop the code
for(ind=count-newcount;ind<count;ind++)/////
{
ri[ind]=newi[ind-count+newcount];
ci[ind]=newj[ind-count+newcount];
}
not only add new elements to the end of index arrays 'ri' and 'ci', but also changed the first element of 'ri', and then mess up everything.
My question is that how this happens. Is it a problem caused by using array with variable length? Should I avoid using arrays with variable length?
It seems that you misinterpret the term VLA. It doesn't means that the size of the array may vary, but that you can dynamically decide what is the size of the array (but the size is fixed once).
You are adding more element to ri and ci without having reallocate them...
I suggest you to, first use dynamic allocation:
int *ri = calloc(sizeof(int),count); //array that stores the row index of trial points;
if (ri==NULL) { /* error */ }
int *ci = calloc(sizeof(int),count);
if (ci==NULL) { /* error */ }
then add two lines just before your problematic loop as:
int *ri2 = realloc(ri,count*sizeof(int));
if (ri2==NULL) { /* error */ }
ri = ri2;
int *ci2 = realloc(ci,count*sizeof(int));
if (ci2==NULL) { /* error */ }
ci = ci2;
In between these portion of code, count may change!
--- EDIT ---
You need to also take care about Alex's answer...
Yes, that is what is causing the problem. While you still have not said what your n is, so the problem described in the other poster's answer might also be applicable; however, there are also problems within the code you posted.
When you say statements like
c[i][j+1]='t';
In case i == n, then
c[i][j+1] = c[i][n+1] = c[i+1][0]
This is because your array is n+1 x n+1, so any time you access the n+1-st entry, it spills over into the next index.
If you check whether i == n before attempting to set the value, then you would avoid this error.
I am confused in understating the behavior of the code while searching for an element which does not exist in the array.
The result of the element index i am looking for is always zero while declaring it as int index;.
The result of the element index i am looking for is random number while declaring it as size_t index;
what is the difference between declaring the variable index as int index; andsize_t;in the code below.
The code
#include <stdio.h>
#define SIZE 5
int main(void)
{
int numbers[SIZE]={1,2,3,4,5};
int search =0; // This variable define the required number i am searching for
int start = 0 ;
int end = SIZE-1 ;
size_t index;
while (start <= end)
{
int middle = (start+end)/2;
if (search == numbers[middle])
{
index = middle;
}
if (search > numbers[middle])
{
start = middle+1 ;
}
else
{
end= middle-1 ;
}
}
printf("The index of the element is %d",index);
return 0;
}
The basic problem is that index is not initialized and that it never gets assigned when you don't find what you are searching for. Since the printf statement accesses an uninitialized variable in that case, your code have undefined behavior, i.e. anything may happen - including print of all sorts of numbers.
The result of the element index i am looking for is always zero while declaring it as int index;
That is "just by luck"
The result of the element index i am looking for is random number while declaring it as size_t index;
That is also "just by luck"
Here are a couple of action items you can take to improve your code:
Since this array is statically defined there is no need to include the SIZE define inside the []. Declare it like this int numbers[]={1,2,3,4,5}; instead of this int numbers[SIZE]={1,2,3,4,5};. Let the compiler do the math for you.
Initialize index to some value (i.e. index = 0;). this is the main cause of the problem and it is introducing undefined behavior to the program.
Change the type of size_t index to int index every variable that was declared in the program is an int and the program is treating index as an int. So it might as well be an int to avoid confusion.
Make this an else if clause instead of just an if:
else if (search > numbers[middle])
{
start = middle+1 ;
}
Add another case to have the program fail gracefully when the value to be searched is missing from the data set. Such as, printf("Data not found: %d", search);
The algorithm still isn't 100% and has some flaws but I will leave this up to you to figure out. I hope this info helps!
Best Regards!
The problem is that , the value of indexis not initialized.
initializing the variable to 0 does not solve your problem.
Because you are using index to return the position of the array element.
By initializing the index = 0 will provide he same result for the elements not present in the array as well as the for the first element to the of the array .
The better way is to initialize as size_t index = -1;
So that the result for the elements not present in the array would b -1.
Also check for the access specifier used in the printf statement, for size_t datatype. It can be ,
printf("The index of the element is %ld",index);
You are not using correct specifier for size_t, it's not %d.
Try to use %zd or %ld and it'll work fine.
Furthermore, add this after the while loop so that it doesn't show weird value of index when the element is not present in the array.
if(start>end) {
printf("That number is not present in the array");
return 0;
}
And move the line printf("The index of the element is %d",index); under the condition if (search == numbers[middle]). So that you don't get "this number is not present" even if it is present in the array.
For corrected version of your code see https://code.hackerearth.com/80043dg?key=7b325b26aec0f5425b76cc3efbdc93cf
My professor suggested that we should also pass a integer size as the parameter :
int abc(const int data[], int size, int value) {
int i= 0, ans= -1;
while (i < size && ans == -1) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
However, I don't think it is necessary to add the integer size in the parameter.
I think the function can be changed to:
int abc(const int data[], int value) {
int i= 0, ans= -1;
while (data[i]!=NULL) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
(I know that we are just passing the pointer of the first element of the array in to the function!)
Is the first version has more advantage than the second version?
data[i] being an int value should not be compared against NULL. That's just not correct.
You should pass the size as a separate parameter.
Passing the size as a parameter is a good practice that can protect you from a segmentation fault if the array is malformed.
If you are absolutely certain that the array will contain 0 (which is what NULL is) as a last value, and only as the last value, your solution would also work.
However, if 0 is a valid value in the array, then you will stop as soon as you encounter it.
while (data[i]!=NULL) - there is no guarantee that data[size] would be equal to NULL as you suggested it would be. Without specifying size of the array, the value of data[size] could in fact be anything.
Note that accessing an array out-of-bound results in undefined behaviour. You will just get whatever value left over in that particular memory location, which can be gibberish, and no guarantee of any specific value (including NULL).
Yes, the first version has one major advantage: it actually works!
There are two reasons why yours won't:
Your version loops until NULL is found. NULL is either a pointer to 0 (which will not work), or 0. So what if there are zeroes in the array? You will get early termination.
Your version has not way of knowing when to stop. What if value is not found in the array? You will go on and on and on until there just happens to be 0 in memory. Arrays are not terminated with 0, only character literals are.
data[i]!=NULL for this to work, the element after the last element of the array should be NULL, which I think won't be the case. int cannot be compared with NULL.
However, you can do something similar. You can use a marker to mark the end of the array
Choose some number that you are sure won't appear in the array (may be you know the range of numbers in the array), lets say 99999. Then save it after the last element (do remember you need an array of size one more then the elements you wanna keep). And then use that to check the end of array.
int abc(const int data[], int value) {
int i= 0, ans= -1;
while (data[i]!=99999) {
if (data[i] == value)
ans= i;
i++;
}
return ans;
}
If there is no information about the range
Then you have to send the size of the array along with other parameters to the function.
I have just started leran about C++. And I have to do one exercise but I don't know how. Please help me.
I have to write the function which returns the position of the number in the array,rate and size are pass to this function and the value of the expression|tab[i]_M| is the maximum, where M is the average of all the elements.
Thank you for your help
You will want to look at the values in your array one by one. You can access the individual values like this:
yourarray[index]
The best way to do it is a loop. There are several loops available in C++. You can use the for loop for example. Inside of the loop you check if the value is the one you are looking for
for (int i = 0; ...
{
if your array[i] == your value
If you found the value, break the loop and return the index i.
// Returns the index of the first occurrence of a value in the array, or -1 if not found
int GetPositionInArray(int array[], int value)
{
for (int i = 0; i < sizeof(array)/sizeof(int); i++) {
if (array[i] == value)
return i;
}
return -1;
}
I have an array: array[3][3]
I will let the user input data into the array as long as it is not full. As soon as the array gets full I want to stop the user from inserting more data into it.
C has no array bounds check. You have to do it yourself. Use a variable to keep track of how many items you have inserted, and stop when your counter is equal to the array size.
You cannot check if "array is full". To do what u want to do, keep track of index while adding elements to array.
You need to keep track of the data inserted by a user. When your counter reaches the size of the array, the array is full. :D There is not other way in C to achieve this result as it does not provide any means of verifying how many elements are in the array.
Introduce a variable for counting the number of cells filled. You adjust this variable whenever you add/remove data to your array. Then, in order to check if your array is full, just check if this variable is equal to the total number of cells in your array.
The most simple way in my opinion is to dynamically allocate memory using calloc(), where you can initialise the array elements to, for example, zeros. The you can check if the array is full by checking, if the last element in the array is still zero or not. Of course, if the last element is still zero, then the array is not full.
First of all this is not an array but a matrix (aka array of array). you already know that the matrix has dimensions 3x3 and then you could do something like this:
int x, y;
int array[3][3];
for (x = 0; x<2; x++)
{
for (y = 0; y<2; y++)
{
//I assume that it is an array of int
printf("Insert number at %d - %d" ,x,y);
scanf("%d" ,&array[x][y]);
}
}
Now the user can only insert 3*3=9 values.
There are no way to array bound check in C, However with better coding practice we check whether array is full.
For example, consider in your array a[3][3] you don't want to have some particular value. That value could be anything! 0xFF or 0 or anything which is in the integer range! and you have to make sure that value is never given as the input to the array, and then you can verify whether your array a[3][3] is full!
/*part of coed in main*/
/*here initialize the array with 0, assuming that 0 will never be a part of array a[3][3]*/
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
a[i][j] = 0; // assuming that 0 will never be a part of array a[3][3]
}
}
while(CheckArray(**a)!=0)
{
printf("give array input:\n")
scanf("%d", &a[row][column]); //writing to empty cell of an array
}
//CheckArray code
int CheckArray(int a[][])
{
for(i=0; i<3; i++)
{
for(j=0;j<3;j++)
{
if(a[i][j] == 0) // assuming that 0 will never be a part of array a[3][3]
{
row = i; // row and column must be global variables in this example!
column = j; // row and column must be global variables in this example!
return 1;
}
else
{
// no need to do anything here
}
}
}
//if code reaches here then array is full!
printf("Array is full.\n");
return 0;
}
You can still optimize the above code! this is just one way of checking whether array is full with better coding practice!
If possible, you could initialize all elements in the array to a certain value that your program would otherwise consider "illegal" or "invalid". E.g. an array of positive numbers can be initialized to be all -1's. Or an array of chars can be initialized to be all NULL characters.
Then, just look at the last element if it is set to the default value.
measurement = sizeof(myarray) / sizeof(element); //or just a constant
while(myarray[measurement-1] == defaultvalue){
//insert code here...
}
Encapsulate the behavior into a struct with getter/setter functions that check for the max length of the desired vector:
typedef varvector
varvector;
struct varvector {
int length;
void* vector;
};
varvector* varvector_create(int length) {
varvector* container = malloc(sizeof(varvector));
void* vector = malloc(length);
if(container && vector) {
container->vector = vector;
}
return(container);
}
void varvector_destroy(varvector* container) {
free(container.vector);
free(container);
}
varvector_get(varvector* container, int position) {
if(position < container.length) {
return(container->vector[position]);
}
}
varvector_set(varvector* container, int position, char value) {
if(position < container.length) {
container->vector[position] = value
}
}
Object Oriented Programming is a design pattern which happens to have syntactic support in some languages and happens to not have syntactic support in C.
This does not mean that you cannot use this design pattern in your work, it just means you have to either use a library that already provides this for you (glib, ooc) or if you only need a small subset of these features, write your own basic functions.
You can assume that the last element of an array has id=0.
Then in function add check if there is an element with id=0.
int add(char *source, char *target, int size) {
int index = 0;
for (int i = 0; i < size; i++) {
if (target[i].id == 0) {
index = i;
break;
}
}
if (index >= 0 && index < size) {
if (index < size - 1) target[index + 1].id = 0;
// check that element with id=0 is the last in the array
//write code to add your element here
return index;
}
}