//Function to store select_field
void store_field(int num_fields, unsigned long *lengths,
MYSQL_ROW row, char elect_type[10][100])
{
//Storing select_field below
int i,j,k,g;
for( i=1;i < num_fields;i=i+10)
{
// i+10 so that loop is executed one time only,
// i=1 bcoz 2nd entry is select_type
for (j=0;j<lengths[i];j++)
{
if (row[i] != NULL)
{
select_type[k][j] = *row[i];
row[i]++;
}
if (row[i] == NULL)
{
select_type[k][j]= '\0';
printf ( "NULL\n");
break; // row[i] is null for fields containing NULL
}
}
for (j;j<100;j++)
{
select_type[k][j]='\0';
}
// setting every other empty field in current row
// of select_type to NULL
}
k++;
}
g = k; //HERE I AM GETTING THE ERROR
for (k;k<10;k++){for(j=0;j<100;j++)
{
select_type[k][j]='\0';
}
}
I have already declared k in the function but I am getting the error.
If you get "not in a function", that means that the code being flagged is, wait for it, not in a function.
Probably a mis-matched closing brace (}) that causes your function to end before you think it does.
I gave up on re-formatting your code to find the problem.
You've got an extra closing bracket. The line
} g=k; **//HERE I AM GETTING THE ERROR**
closes the function.
I took the liberty of formatting out the code indentation. If you maintain good indentation it should be clear that the } is out of place:
#include <stdio.h>
#include <ctype.h> // For tolower() function //
//Function to store select_field
void store_field(int num_fields,unsigned long *lengths,MYSQL_ROW row,char select_type[10][100]){
//Storing select_field below
int i,j,k,g;
for( i=1;i < num_fields;i=i+10){ // i+10 so that loop is executed one time only , i=1 bcoz 2nd entry is select_type
for (j=0;j<lengths[i];j++){
if (row[i] != NULL){ select_type[k][j] = *row[i];
row[i]++;
}
if (row[i] == NULL) { select_type[k][j]= '\0'; printf ( "NULL\n");break; // row[i] is null for fields containing NULL
}
}for (j;j<100;j++){select_type[k][j]='\0';} //setting every other empty field in current row of select_type to NULL
} k++;
// } g=k; **//HERE I AM GETTING THE ERROR**
for (k;k<10;k++){for(j=0;j<100;j++){select_type[k][j]='\0'; }}
}
You should always indent your code to avoid this kind of error. You can find different indentation styles, choose the one you like the most
http://en.wikipedia.org/wiki/Indent_style
There are also automatic indentation tools, below is your code correctly indented
void store_field(int num_fields,unsigned long *lengths,MYSQL_ROW row,char select_type[10][100])
{
int i,j,k,g;
for( i=1;i < num_fields;i=i+10)
{
for (j=0;j<lengths[i];j++)
{
if (row[i] != NULL)
{
select_type[k][j] = *row[i];
row[i]++;
}
if (row[i] == NULL)
{
select_type[k][j]= '\0';
printf ( "NULL\n");
break; // row[i] is null for fields containing NULL
}
}
for (j;j<100;j++)
{
select_type[k][j]='\0';
}
}
k++;
}
g=k; **//HERE I AM GETTING THE ERROR**
for (k;k<10;k++){for(j=0;j<100;j++)
{
select_type[k][j]='\0';
}
}
}
All the errors and extra brackets become evident immediately. Check for some code style guides, there many, choose one you like and stick to that one.
Related
I am trying to write a code that removes comment from a given file [C-Style].
The code that I have written for the function to remove comment is as below. I have passed the source file content in char *copy.
char *remove_comment(char *copy) //if blank file
{
int length = strlen(copy);
int i,j;
for(i=0; i<length; i++)
{
j=i;
if(copy[j++]=='/')
{
if((copy[j]!='\0') && (copy[j]=='/')) //single line comment
{
while((copy[j]!='\0') && ((copy[j]!='\n') || ((copy[j]!='/') && (copy[j+1]!='/'))));
if(copy[j]!='\0') j++; // Safety: INC beyond NULL would give unpredictable results
memmove(copy[i],copy[j],length-j); //replace comments
}
/*
else if((copy[j]!='\0') || (copy[j]=='*')) //multi line comment
{ //later
}
*/
printf("%s",copy);
}
}
return copy;
}
The code seems to be not doing what I expected. Can someone help me understand what am I doing wrong?
This is the question I'm working on : http://www.geeksforgeeks.org/recursively-remove-adjacent-duplicates-given-string/
Here's my code in Java for one pass :
/*If a character isn't repeating, copy it to str[j].
* Find start and end indices of repeating characters. Recursively call again
* And starting position now should be end+1. Pass j and starting position */
public class removeDuplicates {
public static void main(String[] args)
{
char[] str = {'c','c'};
removeDups(str,0,0,0);
System.out.println(str);
}
public static void removeDups(char[] str,int j, int start,int flag)
{
/*Check if start character is repeating or not. If yes , then loop till you find
* another character. Pass that characters index(new start) into a recursive call*/
if(start == str.length-1)
{
if(flag!=1)
{
str[j] = str[start];
j++;
}
if(j<=str.length-1)
{
str[j] = '0';
}
}
while(start<str.length-1 && str[start]!='0')
{
if(str[start+1]!=str[start])
{
str[j] = str[start];
start++;
j++;
if(start==str.length-1) {removeDups(str,j,start,flag);}
}
else
{
char ref = str[start];
while(str[start]==ref)
{
if(start<str.length-1)
{
start++;
}
else
{
flag =1;
break;
}
}
removeDups(str,j,start,flag);
return;
}
}
}
}
This works as expected. Here I'm just trying to use a 0 instead of \0 character as in C. Now when I translate the code to C
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void removeDups(char *str,int j, int start,int flag)
{
/*Check if start character is repeating or not. If yes , then loop till you find
* another character. Pass that characters index(new start) into a recursive call*/
if(start == strlen(str)-1)
{
if(flag!=1)
{
str[j] = str[start];
j++;
}
if(j<=strlen(str)-1)
{
str[j] = '\0';
}
}
while(start<strlen(str)-1 && str[start]!='0')
{
if(str[start+1]!=str[start])
{
str[j] = str[start];
start++;
j++;
if(start==strlen(str)-1) {removeDups(str,j,start,flag);}
}
else
{
char ref = str[start];
while(str[start]==ref)
{
if(start<strlen(str)-1)
{
start++;
}
else
{
flag =1;
break;
}
}
removeDups(str,j,start,flag);
return;
}
}
}
int main()
{
char str[] = "abcddcba";
int len =
while()
for(int i=0;str[i]!='\0';i++)
{
printf("%c",str[i]);
}
printf("\n");
}
The above code gives different results as compared to the Java code.Its virtually identical , just that I'm using strlen() instead of str.length(as in Java).
The interesting part is : if I change the portion to
if(j<=strlen(str)-1)
{
str[j] = '\0';
return;
}
it works perfectly. I've just added a return statement to the if statement.
Why is this happening ? Identical code producing different results in C and Java
You are using return statement and subsequently all code below that return is being excluded from running for that iteration.
Also, You may want to understand what is \0 is and how it's different than 0.
Here's link:
What does the \0 symbol mean in a C string?
In C, assigning a character in a string to '\0' changes the length, so strlen() will return a different result after that. In your Java code, you're using an array, and an array length never changes. You're setting the character to '0' instead of '\0', which are two different things, but even if you did set it to '\0', it still wouldn't change the length. I haven't examined your entire code, but this is one obvious thing that would cause different results.
I have a code like this
int i;
for(i=0; i<n ; i++)
{
....
char* ref_error = "";
if( isSeatAvailable(&tmp, movie_name, seat_number, &ref_error) == 0)
{
printf("available %s\n", seat_number);
}
else
{
logError(ref_error);
}
....
}
If isSeatAvailable returns 0, it works perfectly, but it returns -1 and the program continues to else statement, the variables breaks down: like n becomes 4509408 etc.
The thing is,
If I re-write code like this and call isSeatAvailable method outside of if statement, it works perfect!
int i;
for(i=0; i<n ; i++)
{
....
int res = isSeatAvailable(&tmp, movie_name, seat_number, &ref_error);
if( res == 0)
{
printf("available %s\n", seat_number);
}
else
{
logError(ref_error);
}
....
}
What might cause the problem here?
Here's the method I'm calling
int isSeatAvailable(hall** halls,char* movie_name,char* seat_no, int ticket_count, char** ref_error)
{
....
sprintf(*ref_error,"Seat %s is not defined at %s.",seat_no,tmp->hall_name);
....
}
The problem is in the call to sprintf. The first parameter ref_error comes from:
char* ref_error = "";
And now sprintf tries to overwrite the constant "" with the error message. Strange things will follow!
sprintf needs a real buffer (of sufficient size) to store the message into. Not just a pointer.
I'm trying to print an array of structs that contain two strings. However my print function does not print more than two indices of the array. I am not sure why because it seems to me that the logic is correct.
This is the main function
const int MAX_LENGTH = 1024;
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
} Song;
void getStringFromUserInput(char s[], int maxStrLength);
void printMusicLibrary(Song library[], int librarySize);
void printMusicLibraryTitle(void);
void printMusicLibrary (Song library[], int librarySize);
void printMusicLibraryEmpty(void);
int main(void) {
// Announce the start of the program
printf("%s", "Personal Music Library.\n\n");
printf("%s", "Commands are I (insert), S (sort by artist),\n"
"P (print), Q (quit).\n");
char response;
char input[MAX_LENGTH + 1];
int index = 0;
do {
printf("\nCommand?: ");
getStringFromUserInput(input, MAX_LENGTH);
// Response is the first character entered by user.
// Convert to uppercase to simplify later comparisons.
response = toupper(input[0]);
const int MAX_LIBRARY_SIZE = 100;
Song Library[MAX_LIBRARY_SIZE];
if (response == 'I') {
printf("Song name: ");
getStringFromUserInput(Library[index].songName, MAX_LENGTH);
printf("Artist: ");
getStringFromUserInput(Library[index].artist, MAX_LENGTH);
index++;
}
else if (response == 'P') {
// Print the music library.
int firstIndex = 0;
if (Library[firstIndex].songName[firstIndex] == '\0') {
printMusicLibraryEmpty();
} else {
printMusicLibraryTitle();
printMusicLibrary(Library, MAX_LIBRARY_SIZE);
}
This is my printing the library function
// This function will print the music library
void printMusicLibrary (Song library[], int librarySize) {
printf("\n");
bool empty = true;
for (int i = 0; (i < librarySize) && (!empty); i ++) {
empty = false;
if (library[i].songName[i] != '\0') {
printf("%s\n", library[i].songName);
printf("%s\n", library[i].artist);
printf("\n");
} else {
empty = true;
}
}
}
I think the problem is caused due to setting : empty = true outside the for loop and then checking (!empty) which will evaluate to false. What I am surprised by is how is it printing even two indices. You should set empty = false as you are already checking for the first index before the function call.
The logic has two ways to terminate the listing: 1) if the number of entries is reached, or 2) if any entry is empty.
I expect the second condition is stopping the listing before you expect. Probably the array wasn't built as expected (I didn't look at that part), or something is overwriting an early or middle entry.
you gave the definition as:
typedef struct song
{
char songName[MAX_LENGTH];
char artist[MAX_LENGTH];
}Song;
the later, you write if (library[i].songName[i] != '\0') which really seems strange: why would you index the songname string with the same index that the lib?
so I would naturally expect your print function to be:
// This function will print the music library
void printMusicLibrary (Song library[], int librarySize) {
for (int i = 0; i < librarySize; i ++) {
printf("%s\n%s\n\n", library[i].songName,
library[i].artist);
}
}
note that you may skip empty song names by testing library[i].songName[0] != '\0' (pay attention to the 0), but I think it would be better not to add them in the list (does an empty song name make sens?)
(If you decide to fix that, note that you have an other fishy place: if (Library[firstIndex].songName[firstIndex] == '\0') with the same pattern)
I need to write a function that will return true if it has found a difference between members of an array.
My code is:
int func1(int *str)
{
int i;
for(i=0;i<*(str+i);i++) {
if(*(str+i) == *(str+i+1))
{
return 1;
}
}
return 0;
}
I have to implement it with pointers.
The code above does not work(logically).
Can anybody help?
UPDATE:
I have changed my code to the following:
int func1(int *str)
{
int i,temp=0;
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
What is the problem with the new code?
This looks like homework to me, so I don't want to spoil the fun but one thing about C I'd like to mention: having a pointer to some array doesn't tell you anything about the size of the array. So your function will need to take a pointer and a second size_t argument (or maybe a pointer to the last element of the array).
Your function only takes in a single array pointer, that seems like one too few for a comparison.
You must add an argument that specifies the lengths of the arrays, or implement some kind of "policy" that e.g. terminates the arrays using a specific value.
You should also look into using the standard memcmp() function.
I don't understand the question (It's unclear what you're trying to achieve)...
As others have already said, there's no boundary checking on your array, which is wrong...
Here's some other feedback on your code:
// func1 - consider giving functions a meaningful name, it helps people to
// understand what the function is supposed to be doing....
// In this instance, it might have been helpful to identify what the expected
// return values / inputs of the function are...
int func1(int *str)
{
int i;
// Start a counter at 0, loop (adding 1) while
// the current value of the counter is less than, the value held in the
// array so, {1,2,3,4,0,7} Would terminate on the 0
// This: {1,20,7,14,0,7} Would also terminate on the 0
// This seems wrong, but again, it's unclear what you're trying to do here.
for(i=0;i<*(str+i);i++) {
// If the current element of the array
// is the same as the next element of the array
if(*(str+i) == *(str+i+1))
{
// return 1 - two numbers next to each other in the
// array are the same?
return 1;
}
}
// Either: The array contained a digit less than the counter,
// Or: It didn't contain two numbers that were the same next to each other.
// This seems a bit wrong?!?
return 0;
}
Your question could be improved (to get a more useful answer), if you showed what inputs you were expecting to return what return values.
Based on this 'I will need to write a function that will return true if its found diffrence between members of array.'
In pseudo code, it seems like you would want:
// Loop, checking we don't overflow. No point checking the last element as
// there's nothing after it to check...
for (count = 0 to arraysize -1) {
// If the current element != the next element, we've found a difference?!?
if(arrayElement[count] != arrayElement[count+1) {
return true
}
}
return false
UPDATE:
In your new code...
// You're still assuming the size of 'str'
int func1(int *str)
{
int i,temp=0;
// Loop while i < 9, i.e. 9 times.
for(i=0;i<10-1;i++) {
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
// Maybe it should be (temp == 10-1), but I don't know where the
// 10 comes from...
if( temp == 10 )
{
return 1;
}
}
}
return 0;
}
This:
if(*(str+i) == *(str+i+1))
{
temp++;
// Temp can never == 10, you're only going round the loop 9 times...
if( temp == 10 )
{
return 1;
}
}
Could be:
// return 0 (FALSE) on first difference
if(*(str+i) != *(str+i+1))
{
return 0;
}
If you changed the return 0 at the end of your function to return 1