I am learning to use C in my operating systems class and this is what I have so far for my function to find the intersection of two arrays.
An intersection basically is when you take two sets and you get ONLY the elements that are in both sets.
So for example if set A contains = {1,2,3} and set B contains = {2,3,4} then the intersection of A and B are {2,3}. I'm trying to create a function in C that gets two arrays and returns an array containing integers that are in both passing arrays.
I think I almost have the solution here, but I'm getting an error that says:
"identifier 'count' is undefined"
int intersection(int array1[4], int array2[4])
{
int arrayReturn[sizeof(array1) + sizeof(array2)]
int count = 0;
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 4; j++)
{
if(array1[i]==array2[j])
{
count = count + 1;
arrayReturn[count] = array1[i];
}
}
}
}
I'm very used to Java and I feel like Java and C are nearly identical. I can't really find what's wrong here since count is well within its scope inside the if statement. I don't see how count is undefined.
What's wrong with count and how could I fix this intersection function?
You are missing a semi-colon in the line before count declaration.
int arrayReturn[sizeof(array1) + sizeof(array2)]; //Semicolon Here
int count = 0;
How did I see the error ?
The error message was identifier 'count' is undefined so the first thing I checked for is the cause that the compiler told me. That however was not the problem, as the declaration is there, and in the correct scope. So, now what should I do ? I should look at the line just before the initialization of the variable and at the line just before the usages. This is where you will most certainly find the error.
In short, when the compiler messages don't seem helpful, don't stop. Look around.
Also, as GRAYgoose124 points out, you should have a return statement at the end of your function body as your function is supposed to return an integer.
Missing a semi colon on this line:
int arrayReturn[sizeof(array1) + sizeof(array2)]; //semicolon was missing
As AshRj points out, you are missing a semicolon.
Tip: The clang compiler is excellent at giving diagnostic output. If you try to compile your code with it, you get the following output:
source.c:3:57: error: expected ';' at end of declaration
int arrayReturn[sizeof(array1) + sizeof(array2)]
^
;
Even if you're not compiling your project with clang normally, you can try to compile snippets to help you find out what's wrong. That's what I did with your snippet, as you can see here. (Note the warnings as well.)
void readArr(int arr1[],int n1, int arr2[],int n2,int arr3[]){
int n=0;
int j=0;
for(j=0;j<n1;j++){
for(int k=0; k<n2;k++){
if(arr1[j]==arr2[k]){
int element = arr1[j];
int k=checkArrayContains(arr3,n,element);
if(k==1){
printf("%d\n",arr1[j] );
arr3[n]=arr1[j];
n++;
}
}
}
}
displayArray(arr3,n);}
I think this implementation is more clear.
Related
I am quite new to C so my apologies if this is a straight forward problem but I cannot seem to find my error. My code is as follows
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* makeString(char character,int count)
{
int i;
char* finalString=malloc(count+1);
for(i=1;i<=count;i++)
{
finalString[i]=character;
}
finalString[count]=0;
return finalString;
}
int main()
{
char* string=makeString('*',5);
printf("%s\n",string);
}
I am trying to get an output of the finalString which would be 'character', 'count' number of times. I am not getting any errors or warnings but It is not generating any output. When debugging it runs the loop successfully but does not ever store any character into finalString. Any help appreciated.
As with many programming languages, C uses 0-based indices for arrays. The first element of the character array at finalString is finalString[0], not finalString[1].
Your for loop should go from 0 to count - 1, instead of from 1 to count. The line:
for(i = 1; i <= count; i++)
should instead be:
for(i = 0; i < count; i++)
As your code is now, you have undefined behaviour, because you try to print finalString[0], which is uninitialized. In this case, it seems to be 0 ('\0').
I've ignored the fact that makeString is missing its closing }, since you say this compiles correctly, I assume that's a pasting error.
Arrays in C begin at 0, i.e. the 1st element is finalString[0].
Since you do not set it, it contains garbage, and most probably a NUL which ends the string immediately.
Your loop should look like
for(i=0;i<count;i++)
...
and so on.
Why this program can compiling and run but the result is out of my expectation?`
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i++)
{
printf("%c",message[i]);
}
return 0;
}
But this one can meet my expection.(print "hello" rightly)
int main(void)
{
char *message="hello";
for(int i=0;*message!='\0';i++)
{
printf("%c",*message++);
}
return 0;
}
In the C language,arr[i] is equal to *arr.But in the cases I show above,the result is totally different,when I run them in the devc++.Due to my limited knowledge ,I can't understand this.
Because I'm a student who is going to be a freshman after this summer vacation and only have some konwledge about C language,please answer my question in a more acceptable way. Thanks in advance!
***sorry ,the problem is caused because of my carelessness.I have learned my mistake.
In the C language, arr[i] is equal to *arr....
No, *arr is equal to arr[0].
In your first example, you type message++ which make et points on the next character.
So, the first code can be corrected that way:
for(int i=0; message[i]!='\0'; i++)
{
printf("%c",message[i]);
}
And the second can be simplified: (you don't need i):
for( ;*message!='\0'; )
{
printf("%c",*message++);
}
In the first code, the pointer message isn't changed and what the pointer message points at is also not changed, so the condition *message!='\0' is always true (doing 'h'!='\0').
Therefore, i will continuously be incremented and become so large that message[i] goes out of a region where access is allowed.
The condition should be message[i]!='\0' to avoid this error.
If you want to stick to use * operator for some reason, it should be *(message+i)!='\0'.
I rewrite the program with a slightly different appearance
#include<stdio.h>
int main(void)
{
char *message="hello";
for(int i=0; 'h'!='\0';i++) // notice the change here
{
printf("%c",message[i]);
}
return 0;
}
You see the problem now?
*message is always h, it's not changing with the loop iteration. The comparison is meaningless here, it does not terminate the loop as expected.
You need to ensure that you change the pointer to the next address every time you iterate, to ensure you are checking the value of the next element.
You can make use of the index value, like
for(int i=0; * (message + i) !='\0';i++)
Just writing some code to sort an array using bubble sort, but right at the start I couldn't even define an array and print it.
Code:
#include <stdio.h>
int main () {
int test[] = {9,9,9,9,9}; //define array
test[2] = 3;
bool checker = false; //is it sorted?
int i = 0;
for(int i = 0; i<=4; i++) //set random numbers for array
{
int g;
g = 4+i;
test[i] = g;
i++;
}
for (int i = 0; i <= 4; ++i ) //print array as normal
{
printf(", ", test[i]);
}
When executed it always outputs:
, , , ,
so the array is empty? or im printing it wrong? or something?
You are printing it wrong.
The line in which you are printing should read printf("%d, ", test[i]);
Also not that you have tagged the question as C++, but are using C related terms. Your #include <stdio.h> should be replaced by #include <iostream> and you should be using cout instead of printf for outputting data.
You have two problems in your code.
First, the initial 'for' loop uses 'i' as its counter variable, and your increment condition is 'i++'. That means 'i' automatically increments through each loop iteration; yet within the loop, you specify 'i++', meaning you will see the value of 'i' bumped twice with each pass. Eliminate the extraneous increment.
Second, you are printing the array incorrectly. You need to add a format qualifier such as '%d' to tell printf to use the first argument as a replacement for that specifier.
Lastly, you've indicated C++ for this code, but it really isn't. It's classic C.
I want to initialize an 16-cel-long array with 0, 1, 2 and 3 by blocks of four cels. So here is my first attempt at this:
int main(void) {
int t[16];
int i;
for (i = 0; i<=15; t[i++]=i/4)
{
printf("%d \n", t[i]);
}
return 0;
}
However, here is what I get. I know I can do it differently by just getting the affectation into the for loop, but why does this not work?
EDIT: Please do note that the printf only serves to check what the loop did put in the array.
The initialization works fine; you're just printing the cell before initializing it. Remember that the loop increment is done after each iteration. If you unroll the loop, you have:
i = 0; /* i is now 0 */
print(t[i]); /* prints t[0] */
t[i++] = i/4; /* sets t[0] */
/* i is now 1 */
print(t[i]); /* prints t[1] */
t[i++] = i/4; /* sets t[1] */
/* i is now 2 */
print(t[i]); /* prints t[1] */
/* etc. */
As well as the off-by-one errors with the loop begin/end that have been mentioned in other posts, this code:
t[i++]=i/4
causes undefined behaviour because i is read and written without a sequence point. "Undefined behaviour" means anything can happen: the value could be 3, or 4, or anything else, or the program could crash, etc.
See this thread for more in-depth discussion, and welcome to C..:)
I do not understand what you are trying to accomplish, but please let me show you a similar piece of code, first.
int main(void) {
int t[16];
int i;
//edited the code; providing standard way to do the task
for (i = 0; i<=15; i++)
{
t[i]=i/4;
printf("%d \n", t[i]);
}
return 0;
}
EDIT:
The while loop should be written that way:
int i = 0;
while (i<=15){
t[i] = i%4;
i++;
}
Which means set t[i] equal to i%4 and then increment i.
Since you are a beginner, I've updated the for loop and it now provides a standard way to do your task. It's better to have a simple increment on the third for loop command; do the rest of the job inside the for loop, as described above.
#naltipar: Yeah, I just forgot to initialize the first cel, just like grawity pointed out. Actually, the version I wrote for myself was with i++ but even then, since the third expression is executed after each loop, it sent out the same result. But whatever, it is fixed now.
However, I've got another problem which I'm sure I'm missing on but still can't figure it out:
int i = 0;
while (i<=15)
t[++i] = i%4;
This was first:
for(i = 0; i<=15; t[++i] = i%4);
but it resulted with an infinite loop. So in order to make sure that's not a problem specific to for, I switched to while andthe same thing still happens. That being said, it doesn't occur if i replace ++i by i++. I unrolled the whole loop and everything seems just fine...
I'm a beginner, by the way, in case you were wondering.
A clearer way to write this would be much less error-prone:
for (i = 0; i < 16; ++i)
printf ("%d\n", (t[i] = i % 4));
Personally I'd code something that way, but I'd never recommend it. Moreover, I don't really see much benefit in condensing statements like that, especially in the most important category: execution time. It is perhaps more difficult to optimize, so performance could actually degrade when compared to simply using:
for (i = 0; i < 16; ++i)
{
t[i] = i % 4;
printf ("%d\n", t[i]);
}
Even if it is you reading your own code, you make it difficult for your future self to understand. KISS (Keep It Simple, Stupid), and you'll find code is easier to write now and just as easy to modify later if you need to.
I am having one c code.
Where i had given an array index as 12.But it is allowing me to initialize the array more to that index instead of giving error for index out of bound.
Can any one please explain me y it is happeining.
int vas1[12][12];
vas1[15][15]=0;
int i,j;
for (i = 0; i < 15; i ++)
{
for (j = 0; j < 15; j ++) {
printf("i=%d j=%d vas=%d",i,j,vas1[i][j]);
}
}
printf("Success");
Thanks
C doesn't do bounds checking on array accesses. It simply marks illegal accesses as "undefined behavior" so each implementation can do as it please. Since using C means you know what you're doing, C allows you to shoot yourself in the foot.
In practice, sometimes you will get an error, sometimes not. Sometimes you won't get an error but the client will. Worst case scenario: you won't get an error but the program will behave really weird (variables changing values for no reason etc).