No output for Ingredients Linked List program in C - c
I aim to create a linkedList for food ingredients from a character array stored in a C file (rawRecipies.h). However, upon running the code, nothing shows up in the terminal. Earlier, I was running into a segmentation fault. After tweaking the code, I get no output.
I have checked my code multiple times and have provided enough space for storing the ingredients in my LinkedList. Yet, I cannot find the source of this problem.
You might note that I have added a few exit points in the code. I have done so for debugging, but they are not helpful.
Please let me know what's wrong. Thanks in advance.
Code Below:
#include <stdio.h>
#include <stdlib.h>
#include "rawRecipes.h"
#include <string.h>
#include <stdbool.h>
//ASSUMING THESE LIMITS
#define MAXRECIPES 30 /* max # of recipes */
#define MAXINGREDIENTTYPES 250 /* max # of ingredient types */
#define MAXINGREDIENTS 250 /* max # of ingredients all recipes */
#define MAXCHARS 100 /* max characters for recipe or ingredient*/
#define INGMAX 25 /* max ingredient count per recipe*/
// structure declarations
struct Ingredient {
char IngName[MAXCHARS];
char recipe[MAXRECIPES][MAXCHARS]; //unused member for now.
int recipeNum;
struct Ingredient* next;
};
typedef struct Ingredient Ingredients;
typedef struct linkedListIngredient {
Ingredients* head;
} linkedListIngredient;
// struct for storing items from rawRecipies.h
typedef struct {
char recipe[MAXINGREDIENTS][MAXCHARS];
} records;
Ingredients* createIngredientNode(char value[]) {
Ingredients* newNode = (Ingredients*)malloc(sizeof(Ingredients));
if (newNode != NULL) {
strcpy(newNode->IngName, value);
newNode->next = NULL;
newNode->recipeNum = 0;
return newNode;
}
printf("Failed to create an ingredients node\n");
exit(1);
}
bool IngredientNodeEmpty(linkedListIngredient* list2) {
if (list2->head == NULL) {
return true;
}
else {
return false;
}
}
// append a struct to the back of LinkedList
bool insertIngredientAtBack(linkedListIngredient* list2, char value[]) {
Ingredients* current = list2->head;
if (IngredientNodeEmpty(list2)) {
list2->head = createIngredientNode(value);
return true;
}
else {
while (current->next != NULL) {
current = current->next;
}
current->next = createIngredientNode(value);
if (current->next != NULL) {
return true;
}
else {
printf("Failed to add Ingredient at back\n");
exit(1);
}
}
}
void convertInputToDataStructure(linkedListIngredient* list2, records* items){
char ingredientList[MAXINGREDIENTTYPES][MAXCHARS];
int index;
// Code to find Ingredients and store them in ingredientList.
for(index = 0; (strcmp(items->recipe[index],"") != 0);) {
if(strncmp(items->recipe[index], "1", 1) == 0) {
strcpy(ingredientList[index], (items->recipe[index])+1);
index++;
}
}
// creating a duplicated Ingredient LinkedList:
int i;
for (i = 0; i < index; i++) {
// evaluating and checking the function to add LinkedList for Ingredient
insertIngredientAtBack(list2, ingredientList[i]);
}
}
void ListAllIngredients(linkedListIngredient* list2) {
Ingredients* current = list2->head;
int counter = 1;
while(current->next != NULL) {
printf("Ingredient #%d: %s\n", counter, current->IngName);
counter++;
current = current->next;
}
printf("Recipe #%d: %s\n", counter, current->IngName);
}
int main(void) {
// instantiating the structures for linkedlist access
linkedListIngredient list2;
// holds database for ingredients and recipes
records items;
// copying all values from rawRecipies.h
int i;
for(i = 0; (strcmp(rawRecipes[i], "") != 0); i++) {
strcpy(items.recipe[i], rawRecipes[i]);
}
// first move data from rawRecipes.h to a data structure
convertInputToDataStructure(&list2, &items);
ListAllIngredients(&list2);
}
As mentioned, rawRecipe.h contains a character pointer array. From this array, I am just interested in harvesting the strings that have 1 in front of it for my Ingredients Linked List. These are all the ingredients.
char *rawRecipes[]={
"0Broccoli Coleslaw",
"1olive oil",
"1white vinegar",
"1white sugar",
"1package chicken flavored ramen noodles",
"1broccoli",
"1carrots",
"1green onions",
"1sunflower seeds",
"0Creamy Broccoli Salad",
"1broccoli",
"1red onion",
"1mozzarella cheese",
"1mayonnaise",
"1white sugar",
"1white wine vinegar",
"0Minnesota Broccoli Salad",
"1eggs",
"1broccoli",
"1red onion",
"1green olives",
"1pimentos",
"1mayonnaise",
"1dry mustard",
"1salt",
"1celery seed",
"1dill",
"0Curry Broccoli Salad",
"1broccoli",
"1diced onion",
"1dried cherries",
"1sunflower seeds",
"1mayonnaise",
"1curry powder",
"1cider vinegar",
"1white sugar",
"0Broccoli Buffet Salad",
"1broccoli",
"1red onion",
"1sunflower seeds",
"1raisins",
"1feta cheese",
"1yogurt",
"1mayonnaise",
"1white sugar",
"1lemon juice",
"1salt",
"1pepper",
"0Garlic Broccoli Salad",
"1broccoli",
"1olive oil",
"1pine nuts",
"1rice wine vinegar",
"1vegetable oil",
"1cloves garlic",
"1cayenne pepper",
"1raisins",
"0Alysons Broccoli Salad",
"1broccoli",
"1red onion",
"1raisins",
"1white wine vinegar",
"1white sugar",
"1mayonnaise",
"1sunflower seeds",
"0Broccoli and Ramen Noodle Salad",
"1broccoli coleslaw mix",
"1chicken flavored ramen noodles",
"1green onions",
"1peanuts",
"1sunflower seeds",
"1white sugar",
"1vegetable oil",
"1cider vinegar",
"0Zesty Broccoli and Cauliflower Salad",
"1broccoli",
"1cauliflower",
"1red onion",
"1Italian dressing",
"1sunflower seeds",
"0Mardis Broccoli Salad",
"1broccoli",
"1red onion",
"1jumbo black olives",
"1artichoke hearts",
"1tomatoes",
"1green onions",
"1Italian-style salad dressing",
"0Bops Broccoli Cauliflower Salad",
"1broccoli",
"1cauliflower",
"1Cheddar cheese",
"1red onion",
"1creamy salad dressing",
"1white sugar",
"1white vinegar",
"0Best Baconless Broccoli Salad",
"1broccoli",
"1red onion",
"1dried cranberries",
"1pumpkin seeds",
"1flax seeds",
"1mayonnaise",
"1raspberry vinegar",
"1white sugar",
"1pecans",
"0Broccoli Cauliflower Pepita Salad",
"1broccoli",
"1cauliflower",
"1red bell pepper",
"1onion",
"1pumpkin seeds",
"1mayonnaise",
"1yogurt",
"1red wine vinegar",
"1coconut palm sugar",
"1Dijon mustard",
"1salt",
"0Deli-Style Fresh Broccoli Salad",
"1broccoli",
"1green onion",
"1dried cranberries",
"1mayonnaise",
"1honey",
"1cider vinegar",
"0Broccoli Cauliflower Chickpea Bowl",
"1cashews",
"1broccoli",
"1cauliflower",
"1garlic powder",
"1salt",
"1black pepper",
"1chickpeas",
"1lemon juice",
"1tahini",
"1salt",
"0Broccoli Apple Cranberry Salad",
"1mayonnaise",
"1lemon juice",
"1agave nectar",
"1clove garlic",
"1apple cider vinegar",
"1black pepper",
"1sea salt",
"1broccoli",
"1apple",
"1almonds",
"1carrots",
"1red onion",
"1dried cranberries",
"0Broccoli Mango Salad",
"1ranch dressing",
"1orange juice",
"1horseradish",
"1broccoli",
"1mango",
"1cashews",
"1red onion",
"1mandarin oranges",
"0Asian Pasta Salad with Beef, Broccoli and Bean Sprouts",
"1garlic cloves",
"1soy sauce",
"1rice wine vinegar",
"1sugar",
"1sesame oil",
"1ground ginger",
"1hot red pepper flakes",
"1mayonnaise",
"1vegetable oil",
"1salt",
"1penne pasta",
"1broccoli",
"1carrots",
"1red bell pepper",
"1bean sprouts",
"1green onions",
"1peanuts",
"1cilantro",
"0Easy Broccoli Salad I",
"1broccoli",
"1red onion",
"1raisins",
"1sunflower seeds",
"1yogurt",
"1orange juice",
"1mayonnaise",
"0Minnesota Broccoli Salad",
"1eggs",
"1broccoli",
"1red onion",
"1green olives",
"1pimentos",
"1mayonnaise",
"1dry mustard",
"1salt",
"1celery seed",
"1dill",
"0Delicious Broccoli Cranberry Salad",
"1broccoli",
"1dried cranberries",
"1red onion",
"1chopped celery",
"1mayonnaise",
"1white sugar",
"1rice vinegar",
"1cashews",
"0Fruit and Broccoli Buffet Salad",
"1grapeseed oil",
"1granulated sugar",
"1cider vinegar",
"1lime juice",
"1lime zest",
"1garlic",
"1salt",
"1poppy seeds",
"1paprika",
"1dry mustard",
"1pecans",
"1oranges",
"1broccoli",
"1apple",
"1grapes",
"0Strawberry Broco-Flower Salad",
"1broccoli",
"1cauliflower",
"1carrot",
"1strawberries",
"1slivered almonds",
"1raspberry vinaigrette",
"0Broccoli and Tortellini Salad",
"1cheese-filled tortellini",
"1mayonnaise",
"1white sugar",
"1cider vinegar",
"1broccoli",
"1raisins",
"1sunflower seeds",
"1red onion",
""
};
Related
Hi guys, How do i render these ingredients on react component without having to write out "strIngredient1" through "strIngredient20"
How do I render these ingredients on react component without having to write out "strIngredient1" through "strIngredient20"? Here's a snippet of the JSON file. {"meals":[{ "idMeal":"8000", "strMeal":"Buffalo Cauliflower", "strDrinkAlternate":null, "strCategory":"vegeterian", "strDescription":, "strInstructions":, "strMealThumb":"https://gimmedelicious.com/wp-content/uploads/2016/01/caulfilower-buffalo- wings-15-of-17.jpg", "strIngredient1":"Medium Head Cauliflower", "strIngredient2":"Panko Breadcrumbs", "strIngredient3":"Vegetable Oil", "strIngredient4":"Fine Sea Salt", "strIngredient5":"All-Purpose Flour", "strIngredient6":"Rice Flour", "strIngredient7":"Smoked Paprika", "strIngredient8":"Sweet Paprika", "strIngredient9":"Garlic Powder", "strIngredient10":"Onion Powder", "strIngredient11":"Fish Sauce", "strIngredient12":"Milk", "strIngredient13":"Buffalo Sauce, Such as Frank’s Red Hot", "strIngredient14":"Honey", "strIngredient15":"Celery Stalk, Leaves Included, Thinly Sliced", "strMeasure1":"1", "strMeasure2":"2 cups ", "strMeasure3":"⅓ cup", "strMeasure4":"½ teaspoon", "strMeasure5":"¾ cup ", "strMeasure6":"¼ cup", "strMeasure7":"½ teaspoons", "strMeasure8":"½ teaspoon", "strMeasure9":"1 teaspoon", "strMeasure10":"1 teaspoon", "strMeasure11":"2 teaspoon", "strMeasure12":"½ cup", "strMeasure13":"1 cup", "strMeasure14":"3 tablespoons", "strMeasure15":"1" }]}
You could preprocess each recipe before passing it for rendering. var orig = { idMeal: "8000", strMeal: "Buffalo Cauliflower", strDrinkAlternate: null, strCategory: "vegeterian", strDescription: "", strInstructions: "", strIngredient1: "Medium Head Cauliflower", strIngredient2: "Panko Breadcrumbs", strIngredient3: "Vegetable Oil", strIngredient4: "Fine Sea Salt", strMeasure1: "1", strMeasure2: "2 cups ", strMeasure3: "⅓ cup", strMeasure4: "½ teaspoon", // rest of ingredients removed for brevity }; function processRecipe(recipe) { const processedRecipe = { ...recipe }; const ingredients = []; for (let i = 1; ; i++) { const ingredientKey = `strIngredient${i}`; const measureKey = `strMeasure${i}`; const ingredient = processedRecipe[ingredientKey]; const measure = processedRecipe[measureKey]; if (!(ingredient && measure)) break; ingredients.push([ingredient, measure]); delete processedRecipe[ingredientKey]; delete processedRecipe[measureKey]; } return { ...processedRecipe, ingredients }; } console.log(processRecipe(orig)); With that, the output is e.g. { "idMeal": "8000", "strMeal": "Buffalo Cauliflower", "strDrinkAlternate": null, "strCategory": "vegeterian", "strDescription": "", "strInstructions": "", "ingredients": [ [ "Medium Head Cauliflower", "1" ], [ "Panko Breadcrumbs", "2 cups " ], [ "Vegetable Oil", "⅓ cup" ], [ "Fine Sea Salt", "½ teaspoon" ] ] } and an ingredient list such as that is easy to loop over.
First of all I think you're not using JSON the best way, i'd do something that looks more like that : {"meals":[{ "idMeal":"8000", "strMeal":"Buffalo Cauliflower", "strDrinkAlternate":null, "strCategory":"vegeterian", "strDescription":, "strInstructions":, "strMealThumb":"https://gimmedelicious.com/wp-content/uploads/2016/01/caulfilower-buffalo- wings-15-of-17.jpg", "ingredients": [ {name:"Medium Head Cauliflower", "measure":1}, {name:"Panko Breadcrumbs", "measure": "2 cups"}, // etc ... ] }]} Then in react simply use .map for instance function Meal({meal}) { ... return ( <> {meal.ingredients.map((ingredient)=>{ return ( <div key={ingredient.name}>{ingredient.name} measurement : {ingredient.measure}</div> ) } )} </> ) ... }
how do you access every value inside the hashes within an array in json type of file?
I want to access every value of strIngredient1 key. I am not good yet at coding, but my guess is that I would have to use looping to get it, but don't really know the way to formulate it. JSON file: {"drinks":[{"strIngredient1":"Light rum"},{"strIngredient1":"Applejack"},{"strIngredient1":"Gin"},{"strIngredient1":"Dark rum"},{"strIngredient1":"Sweet Vermouth"},{"strIngredient1":"Strawberry schnapps"},{"strIngredient1":"Scotch"},{"strIngredient1":"Apricot brandy"},{"strIngredient1":"Triple sec"},{"strIngredient1":"Southern Comfort"},{"strIngredient1":"Orange bitters"},{"strIngredient1":"Brandy"},{"strIngredient1":"Lemon vodka"},{"strIngredient1":"Blended whiskey"},{"strIngredient1":"Dry Vermouth"},{"strIngredient1":"Amaretto"},{"strIngredient1":"Tea"},{"strIngredient1":"Champagne"},{"strIngredient1":"Coffee liqueur"},{"strIngredient1":"Bourbon"},{"strIngredient1":"Tequila"},{"strIngredient1":"Vodka"},{"strIngredient1":"A\u00f1ejo rum"},{"strIngredient1":"Bitters"},{"strIngredient1":"Sugar"},{"strIngredient1":"Kahlua"},{"strIngredient1":"demerara Sugar"},{"strIngredient1":"Dubonnet Rouge"},{"strIngredient1":"Watermelon"},{"strIngredient1":"Lime juice"},{"strIngredient1":"Irish whiskey"},{"strIngredient1":"Apple brandy"},{"strIngredient1":"Carbonated water"},{"strIngredient1":"Cherry brandy"},{"strIngredient1":"Creme de Cacao"},{"strIngredient1":"Grenadine"},{"strIngredient1":"Port"},{"strIngredient1":"Coffee brandy"},{"strIngredient1":"Red wine"},{"strIngredient1":"Rum"},{"strIngredient1":"Grapefruit juice"},{"strIngredient1":"Ricard"},{"strIngredient1":"Sherry"},{"strIngredient1":"Cognac"},{"strIngredient1":"Sloe gin"},{"strIngredient1":"Apple juice"},{"strIngredient1":"Pineapple juice"},{"strIngredient1":"Lemon juice"},{"strIngredient1":"Sugar syrup"},{"strIngredient1":"Milk"},{"strIngredient1":"Strawberries"},{"strIngredient1":"Chocolate syrup"},{"strIngredient1":"Yoghurt"},{"strIngredient1":"Mango"},{"strIngredient1":"Ginger"},{"strIngredient1":"Lime"},{"strIngredient1":"Cantaloupe"},{"strIngredient1":"Berries"},{"strIngredient1":"Grapes"},{"strIngredient1":"Kiwi"},{"strIngredient1":"Tomato juice"},{"strIngredient1":"Cocoa powder"},{"strIngredient1":"Chocolate"},{"strIngredient1":"Heavy cream"},{"strIngredient1":"Galliano"},{"strIngredient1":"Peach Vodka"},{"strIngredient1":"Ouzo"},{"strIngredient1":"Coffee"},{"strIngredient1":"Spiced rum"},{"strIngredient1":"Water"},{"strIngredient1":"Espresso"},{"strIngredient1":"Angelica root"},{"strIngredient1":"Orange"},{"strIngredient1":"Cranberries"},{"strIngredient1":"Johnnie Walker"},{"strIngredient1":"Apple cider"},{"strIngredient1":"Everclear"},{"strIngredient1":"Cranberry juice"},{"strIngredient1":"Egg yolk"},{"strIngredient1":"Egg"},{"strIngredient1":"Grape juice"},{"strIngredient1":"Peach nectar"},{"strIngredient1":"Lemon"},{"strIngredient1":"Firewater"},{"strIngredient1":"Lemonade"},{"strIngredient1":"Lager"},{"strIngredient1":"Whiskey"},{"strIngredient1":"Absolut Citron"},{"strIngredient1":"Pisco"},{"strIngredient1":"Irish cream"},{"strIngredient1":"Ale"},{"strIngredient1":"Chocolate liqueur"},{"strIngredient1":"Midori melon liqueur"},{"strIngredient1":"Sambuca"},{"strIngredient1":"Cider"},{"strIngredient1":"Sprite"},{"strIngredient1":"7-Up"},{"strIngredient1":"Blackberry brandy"},{"strIngredient1":"Peppermint schnapps"},{"strIngredient1":"Creme de Cassis"}]}
You could parse the json and map the values: data = {"drinks":[{"strIngredient1":"Light rum"},... parsed_json = JSON.parse(data, symbolize_names: true) strIngredient1s = parsed_json[:drinks].map { |hash| hash[:strIngredient1] }
You can do something like this: require 'json' def retrieve_values(json:) drinks_result = [] JSON.parse(json, {:symbolize_names => true})[:drinks].each do |k, v| drinks_result << v end end drinks_result The above code first parse the JSON you receive as a parameter then iterates over the list of drinks where k is the key of the sub-hashes, example: **k** -> strIngredient1 and v is the value, example: **v** -> Coffee brandy, you can use the code above as follow: retrieve_values(json: json_to_parse). The result is a list with all the values, you can iterate over that list as follow: retrieve_values(json: json_to_parse).each do |drink_i| ...execute your code here end
You have inserted newlines in your string for display purposes. If str is your string your actual strings is presumably json = str.delete("\n") Since require 'json' JSON.parse(json)["drinks"] returns an array of hashes, all of which have the single key "strIngredient1", we may write JSON.parse(json)["drinks"].map { |h| h["strIngredient1"] } or JSON.parse(json)["drinks"].flat_map(&:values) Both return the array: ["Light rum", "Applejack", "Gin", "Dark rum", "Sweet Vermouth", "Strawberry schnapps", "Scotch", "Apricot brandy", "Triple sec", "Southern Comfort", "Orange bitters", "Brandy", "Lemon vodka", "Blended whiskey", "Dry Vermouth", "Amaretto", "Tea", "Champagne", "Coffee liqueur", "Bourbon", "Tequila", "Vodka", "Añejo rum", "Bitters", "Sugar", "Kahlua", "demerara Sugar", "Dubonnet Rouge", "Watermelon", "Lime juice", "Irish whiskey", "Apple brandy", "Carbonated water", "Cherry brandy", "Creme de Cacao", "Grenadine", "Port", "Coffee brandy", "Red wine", "Rum", "Grapefruit juice", "Ricard", "Sherry", "Cognac", "Sloe gin", "Apple juice", "Pineapple juice", "Lemon juice", "Sugar syrup", "Milk", "Strawberries", "Chocolate syrup", "Yoghurt", "Mango", "Ginger", "Lime", "Cantaloupe", "Berries", "Grapes", "Kiwi", "Tomato juice", "Cocoa powder", "Chocolate", "Heavy cream", "Galliano", "Peach Vodka", "Ouzo", "Coffee", "Spiced rum", "Water", "Espresso", "Angelica root", "Orange", "Cranberries", "Johnnie Walker", "Apple cider", "Everclear", "Cranberry juice", "Egg yolk", "Egg", "Grape juice", "Peach nectar", "Lemon", "Firewater", "Lemonade", "Lager", "Whiskey", "Absolut Citron", "Pisco", "Irish cream", "Ale", "Chocolate liqueur", "Midori melon liqueur", "Sambuca", "Cider", "Sprite", "7-Up", "Blackberry brandy", "Peppermint schnapps", "Creme de Cassis"]
Codename One - Flags for all countries
I have a code very similar to the Uber clone app to show a country picker form. I understand that the flags are taken from flagResource = Resources.open("/flags.res");, from the Codename One SMS Library The problem is that a lot of flags are missing. A user may be sorry if the flag of his/her country is not there. How can I insert all the flags?
I wish I knew. I looked a lot for a resource that contains all of the flags in the world and was very disappointed that most were lacking in various ways. After I did all that I thought about using the unicode emojii flags which would be a huge boon as it would also remove the need for images but that wouldn't work in the simulator properly as it doesn't render emojii. It might be interesting to try and enhance the code with support for emojii on devices where it's supported but you will need to actually do the legwork of going through almost 200 countries and finding their flag unicode value... There are some lists but adapting them is a pain.
I found a solution to show all the flags. I'm going to share my code and exactly how I proceeded... STEP 1 - HOW MANY COUNTRY CODES? Complete List of Country & Dialing Codes (248 country codes) - https://www.worldatlas.com/aatlas/ctycodes.htm I compared the previous list with these: https://en.wikipedia.org/wiki/List_of_country_calling_codes (280 country code, but missing of iso codes) https://countrycode.org/ (240 country codes) http://www.countryareacode.net/ (225 country codes) https://www.studyabroad.com/resources/international-calling-codes (234 country codes) https://www.howtocallabroad.com/codes.html (255 country codes, but some of them are repeated) The first list with 248 country codes is probabily the one to be used. Note that 248 country codes were used also by Whatsapp (in the 2016), it's an hint of the right direction: https://www.quora.com/Whatsapp-has-248-flags-in-its-symbols-keyboard-in-its-latest-update-But-there-are-nearly-190-200-countries-on-earth-What-is-it-that-I-am-missing However the current version of Whatsapp has 258 flags (I counted them extracting them from its apk). However, even if I suppose that the flags cannot fall within anyone's intellectual property, I think that it's safer to use flags from an open source repository, like the following one. I'm going to use the 248 country codes list because it's the more suitable for our purposes (in my opinion, after several checkings). STEP 2 - DOWNLOAD THE FLAGS The 248 flags (in SVG format) can be downloaded from: https://github.com/joielechong/iso-country-flags-svg-collection The interesting folder for our purposes is this one: iso-country-flags-svg-collection-master/svg/country-4x3 It contains more flags than the 248 available country codes (they are 262 in total), but it's not a problem (the opposite should be a problem, of course...). I converted all of them to PNGs files with the size of 150x112 pixels with the following command (on Linux with Inkscape installed): for i in *.svg; do inkscape $i --export-width=150 --export-height=112 --export-png=`echo $i | sed -e 's/svg$/png/'`; done You can download these generated PNGs from: http://jmp.sh/vXaA7eC STEP 3 - CREATE NEW ARRAYS FOR THE APP In the Uber clone, we have the following arrays, each of them contains 243 strings: COUNTRY_NAMES (Afghanistan to Zimbabwe, note that Åland Islands is at the end of the list after Zimbabwe, I suppose that it's not correct in alphabetic order... however the country code of Åland Islands is the same of Finland) COUNTRY_CODES (all numeric codes, without the "+") COUNTRY_FLAGS (all the files names of the PNGs, with "null" for some countries) COUNTRY_ISO2 (AL, DZ, AS, etc.) COUNTRY_ISO3 (AFG, ALB, etc.) I replaced the import of these array from com.codename1.sms.activation.ActivationForm.* with the following ones declared in my package (all of them contains 248 strings): public static final String[] COUNTRY_NAMES = {"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bonaire", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Democratic Republic of the Congo", "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Curacao", "Cyprus", "Czech Republic", "Cote d'Ivoire", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran, Islamic Republic of", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macao", "Macedonia, the Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of", "Moldova, Republic of", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestine, State of", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Romania", "Russian Federation", "Rwanda", "Reunion", "Saint Barthelemy", "Saint Helena", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin (French part)", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten (Dutch part)", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan", "United Republic of Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Viet Nam", "Virgin Islands (British)", "US Virgin Islands", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"}; // note: from the original list https://www.worldatlas.com/aatlas/ctycodes.htm, I modified the code of "Dominican Republic", I removed the "-" sign from all codes and I corrected some typos in the country names public static final String[] COUNTRY_CODES = {"93", "355", "213", "1684", "376", "244", "1264", "672", "1268", "54", "374", "297", "61", "43", "994", "1242", "973", "880", "1246", "375", "32", "501", "229", "1441", "975", "591", "599", "387", "267", "47", "55", "246", "673", "359", "226", "257", "855", "237", "1", "238", "1345", "236", "235", "56", "86", "61", "61", "57", "269", "242", "243", "682", "506", "385", "53", "599", "357", "420", "225", "45", "253", "1767", "18", "593", "20", "503", "240", "291", "372", "251", "500", "298", "679", "358", "33", "594", "689", "262", "241", "220", "995", "49", "233", "350", "30", "299", "1473", "590", "1671", "502", "44", "224", "245", "592", "509", "672", "379", "504", "852", "36", "354", "91", "62", "98", "964", "353", "44", "972", "39", "1876", "81", "44", "962", "7", "254", "686", "850", "82", "965", "996", "856", "371", "961", "266", "231", "218", "423", "370", "352", "853", "389", "261", "265", "60", "960", "223", "356", "692", "596", "222", "230", "262", "52", "691", "373", "377", "976", "382", "1664", "212", "258", "95", "264", "674", "977", "31", "687", "64", "505", "227", "234", "683", "672", "1670", "47", "968", "92", "680", "970", "507", "675", "595", "51", "63", "870", "48", "351", "1", "974", "40", "7", "250", "262", "590", "290", "1869", "1758", "590", "508", "1784", "685", "378", "239", "966", "221", "381", "248", "232", "65", "1721", "421", "386", "677", "252", "27", "500", "211", "34", "94", "249", "597", "47", "268", "46", "41", "963", "886", "992", "255", "66", "670", "228", "690", "676", "1868", "216", "90", "993", "1649", "688", "256", "380", "971", "44", "1", "1", "598", "998", "678", "58", "84", "1284", "1340", "681", "212", "967", "260", "263"}; // here I list the file names in the same order of the previous country names and country codes; some unused flags are not listed, because we have more flags than country codes... public static final String[] COUNTRY_FLAGS = {"af.png", "al.png", "dz.png", "as.png", "ad.png", "ao.png", "ai.png", "aq.png", "ag.png", "ar.png", "am.png", "aw.png", "au.png", "at.png", "az.png", "bs.png", "bh.png", "bd.png", "bb.png", "by.png", "be.png", "bz.png", "bj.png", "bm.png", "bt.png", "bo.png", "bq.png", "ba.png", "bw.png", "bv.png", "br.png", "io.png", "bn.png", "bg.png", "bf.png", "bi.png", "kh.png", "cm.png", "ca.png", "cv.png", "ky.png", "cf.png", "td.png", "cl.png", "cn.png", "cx.png", "cc.png", "co.png", "km.png", "cg.png", "cd.png", "ck.png", "cr.png", "hr.png", "cu.png", "cw.png", "cy.png", "cz.png", "ci.png", "dk.png", "dj.png", "dm.png", "do.png", "ec.png", "eg.png", "sv.png", "gq.png", "er.png", "ee.png", "et.png", "fk.png", "fo.png", "fj.png", "fi.png", "fr.png", "gf.png", "pf.png", "tf.png", "ga.png", "gm.png", "ge.png", "de.png", "gh.png", "gi.png", "gr.png", "gl.png", "gd.png", "gp.png", "gu.png", "gt.png", "gg.png", "gn.png", "gw.png", "gy.png", "ht.png", "hm.png", "va.png", "hn.png", "hk.png", "hu.png", "is.png", "in.png", "id.png", "ir.png", "iq.png", "ie.png", "im.png", "il.png", "it.png", "jm.png", "jp.png", "je.png", "jo.png", "kz.png", "ke.png", "ki.png", "kp.png", "kr.png", "kw.png", "kg.png", "la.png", "lv.png", "lb.png", "ls.png", "lr.png", "ly.png", "li.png", "lt.png", "lu.png", "mo.png", "mk.png", "mg.png", "mw.png", "my.png", "mv.png", "ml.png", "mt.png", "mh.png", "mq.png", "mr.png", "mu.png", "yt.png", "mx.png", "fm.png", "md.png", "mc.png", "mn.png", "me.png", "ms.png", "ma.png", "mz.png", "mm.png", "na.png", "nr.png", "np.png", "nl.png", "nc.png", "nz.png", "ni.png", "ne.png", "ng.png", "nu.png", "nf.png", "mp.png", "no.png", "om.png", "pk.png", "pw.png", "ps.png", "pa.png", "pg.png", "py.png", "pe.png", "ph.png", "pn.png", "pl.png", "pt.png", "pr.png", "qa.png", "ro.png", "ru.png", "rw.png", "re.png", "bl.png", "sh.png", "kn.png", "lc.png", "mf.png", "pm.png", "vc.png", "ws.png", "sm.png", "st.png", "sa.png", "sn.png", "rs.png", "sc.png", "sl.png", "sg.png", "sx.png", "sk.png", "si.png", "sb.png", "so.png", "za.png", "gs.png", "ss.png", "es.png", "lk.png", "sd.png", "sr.png", "sj.png", "sz.png", "se.png", "ch.png", "sy.png", "tw.png", "tj.png", "tz.png", "th.png", "tl.png", "tg.png", "tk.png", "to.png", "tt.png", "tn.png", "tr.png", "tm.png", "tc.png", "tv.png", "ug.png", "ua.png", "ae.png", "gb.png", "us.png", "um.png", "uy.png", "uz.png", "vu.png", "ve.png", "vn.png", "vg.png", "vi.png", "wf.png", "eh.png", "ye.png", "zm.png", "zw.png"}; // note that the file names should be lowercase, instead the country iso codes should be uppercase public static final String[] COUNTRY_ISO2 = {"AF", "AL", "DZ", "AS", "AD", "AO", "AI", "AQ", "AG", "AR", "AM", "AW", "AU", "AT", "AZ", "BS", "BH", "BD", "BB", "BY", "BE", "BZ", "BJ", "BM", "BT", "BO", "BQ", "BA", "BW", "BV", "BR", "IO", "BN", "BG", "BF", "BI", "KH", "CM", "CA", "CV", "KY", "CF", "TD", "CL", "CN", "CX", "CC", "CO", "KM", "CG", "CD", "CK", "CR", "HR", "CU", "CW", "CY", "CZ", "CI", "DK", "DJ", "DM", "DO", "EC", "EG", "SV", "GQ", "ER", "EE", "ET", "FK", "FO", "FJ", "FI", "FR", "GF", "PF", "TF", "GA", "GM", "GE", "DE", "GH", "GI", "GR", "GL", "GD", "GP", "GU", "GT", "GG", "GN", "GW", "GY", "HT", "HM", "VA", "HN", "HK", "HU", "IS", "IN", "ID", "IR", "IQ", "IE", "IM", "IL", "IT", "JM", "JP", "JE", "JO", "KZ", "KE", "KI", "KP", "KR", "KW", "KG", "LA", "LV", "LB", "LS", "LR", "LY", "LI", "LT", "LU", "MO", "MK", "MG", "MW", "MY", "MV", "ML", "MT", "MH", "MQ", "MR", "MU", "YT", "MX", "FM", "MD", "MC", "MN", "ME", "MS", "MA", "MZ", "MM", "NA", "NR", "NP", "NL", "NC", "NZ", "NI", "NE", "NG", "NU", "NF", "MP", "NO", "OM", "PK", "PW", "PS", "PA", "PG", "PY", "PE", "PH", "PN", "PL", "PT", "PR", "QA", "RO", "RU", "RW", "RE", "BL", "SH", "KN", "LC", "MF", "PM", "VC", "WS", "SM", "ST", "SA", "SN", "RS", "SC", "SL", "SG", "SX", "SK", "SI", "SB", "SO", "ZA", "GS", "SS", "ES", "LK", "SD", "SR", "SJ", "SZ", "SE", "CH", "SY", "TW", "TJ", "TZ", "TH", "TL", "TG", "TK", "TO", "TT", "TN", "TR", "TM", "TC", "TV", "UG", "UA", "AE", "GB", "US", "UM", "UY", "UZ", "VU", "VE", "VN", "VG", "VI", "WF", "EH", "YE", "ZM", "ZW"}; public static final String[] COUNTRY_ISO3 = {"AFG", "ALB", "DZA", "ASM", "AND", "AGO", "AIA", "ATA", "ATG", "ARG", "ARM", "ABW", "AUS", "AUT", "AZE", "BHS", "BHR", "BGD", "BRB", "BLR", "BEL", "BLZ", "BEN", "BMU", "BTN", "BOL", "BES", "BIH", "BWA", "BVT", "BRA", "IOT", "BRN", "BGR", "BFA", "BDI", "KHM", "CMR", "CAN", "CPV", "CYM", "CAF", "TCD", "CHL", "CHN", "CXR", "CCK", "COL", "COM", "COG", "COD", "COK", "CRI", "HRV", "CUB", "CUW", "CYP", "CZE", "CIV", "DNK", "DJI", "DMA", "DOM", "ECU", "EGY", "SLV", "GNQ", "ERI", "EST", "ETH", "FLK", "FRO", "FJI", "FIN", "FRA", "GUF", "PYF", "ATF", "GAB", "GMB", "GEO", "DEU", "GHA", "GIB", "GRC", "GRL", "GRD", "GLP", "GUM", "GTM", "GGY", "GIN", "GNB", "GUY", "HTI", "HMD", "VAT", "HND", "HKG", "HUN", "ISL", "IND", "IDN", "IRN", "IRQ", "IRL", "IMN", "ISR", "ITA", "JAM", "JPN", "JEY", "JOR", "KAZ", "KEN", "KIR", "PRK", "KOR", "KWT", "KGZ", "LAO", "LVA", "LBN", "LSO", "LBR", "LBY", "LIE", "LTU", "LUX", "MAC", "MKD", "MDG", "MWI", "MYS", "MDV", "MLI", "MLT", "MHL", "MTQ", "MRT", "MUS", "MYT", "MEX", "FSM", "MDA", "MCO", "MNG", "MNE", "MSR", "MAR", "MOZ", "MMR", "NAM", "NRU", "NPL", "NLD", "NCL", "NZL", "NIC", "NER", "NGA", "NIU", "NFK", "MNP", "NOR", "OMN", "PAK", "PLW", "PSE", "PAN", "PNG", "PRY", "PER", "PHL", "PCN", "POL", "PRT", "PRI", "QAT", "ROU", "RUS", "RWA", "REU", "BLM", "SHN", "KNA", "LCA", "MAF", "SPM", "VCT", "WSM", "SMR", "STP", "SAU", "SEN", "SRB", "SYC", "SLE", "SGP", "SXM", "SVK", "SVN", "SLB", "SOM", "ZAF", "SGS", "SSD", "ESP", "LKA", "SDN", "SUR", "SJM", "SWZ", "SWE", "CHE", "SYR", "TWN", "TJK", "TZA", "THA", "TLS", "TGO", "TKL", "TON", "TTO", "TUN", "TUR", "TKM", "TCA", "TUV", "UGA", "UKR", "ARE", "GBR", "USA", "UMI", "URY", "UZB", "VUT", "VEN", "VNM", "VGB", "VIR", "WLF", "ESH", "YEM", "ZMB", "ZWE"}; STEP 4 - Put all together From CountryCodePicker.java and CountryPickerForm.java (of the Uber Clone) remove the import of the arrays from com.codename1.sms.activation.ActivationForm and insert the previous arrays in your package and import them from it. In the Codename One Designer, create a new file 248flags.res and import all the PNG flags generated at the Step 2 (http://jmp.sh/vXaA7eC) with "Images" -> "Quick Add Multiimages", selecting "4K" as source resolution. Wait for a while, it can be a long task... In the CountryCodePicker.java, change: flagResource = Resources.open("/flags.res"); to: flagResource = Resources.open("/248flags.res"); STEP 5 - Result Good news: now there are all the flags!!! :) About the build size, the original flag.res of SMSActivation.cn1lib has a size of 411 kbyte (it's located in lib/impl/cls/flags.res), while my 248flags.res has a size of 2596 kbyte... but the original flag.res uses normal images of about 100x50 pixels, instead I used multiimages that better adapt on different densities. Final check: it's possibile to manually check all country names and codes on Wikipedia and on other resources... if somebody wants to do the check, thanks :)
How can I return the index of the minimum integer in an array?
I'm returning the index of the smallest integer in an array. I found a solution from this forum. Here is what I did: require 'amatch' include Amatch ingredients_arr = [ "All purpose", "Ammoniaco", "Assorted sprinkles", "Baking Powder", "Baking soda", "Banana", "Banana flavor", "Bread improver", "Brown Sugar", "Buko pandan flavor", "Butter", "Butter flavor", "Butter oil subs", "Cake Flour", "Cake emulsi\nfier", "Canyon baking powder", "Cheese", "Chiffon oil", "Choco flavor", "Choco spri\nnkles", "Cocoa (imp)", "Cocoa (loc)", "Coconut", "Condensada", "Cooking\nOil", "\n Corn Starch", "Dessicated", "Dutch choco fudge premium", "Dutch cocoa premium", "Egg", "Evaporad\n a (B)", "Evaporada (S)", "Evaporadaorated\n(B)", "First Class", "Food color", "Glucose", "Go\n ld coin", "Heart sprinkles", "LPG", "Lard", "Linga", "Margarine", "Mocha flavor", "Mongo paste red", "Onion", "Ovalet", "Powdered sugar", "Rhum", "Royal", "Salt", "Sibuyas", "Skim milk (h-end)", "Skim milk (l-end)", "\n Star sprinkles", "Strawberry flavor", "Styro (l. plan)", "Super syrup", "Taba", "Tartar", "\n Third Class", "Ube Paste", "Ube flavor", "Vanilla", "Vanilla 1G", "Vivid icing", "Wash Sugar", "Water", "White Sugar" ] i, ingredient = 1, "Flour" ing_array = Array.new until ingredient == "" puts "Enter ingredient #{i}: " ingredient = gets.chomp ing_array << ingredient i += 1 end ing_array.pop m = Sellers.new("margarine") no_words = ing_array.length ing_index_arr = Array.new i = 0 while i < no_words rating_arr = Array.new m = Sellers.new(ing_array[i]) j = 0 while j < ingredients_arr.length x = m.match(ingredients_arr[j]) rating_arr << x j += 1 end y = rating_arr.each.with_index.find_all{|a, i| a == rating_arr.min }.map{|a, b| b} ing_index_arr << y i += 1 end ing_index_arr # => [[0], [67], [4]] but I need something like this: [0, 67, 4] Hope someone can help me.
If you want to collapse your sub-arrays, use the flatten method. http://ruby-doc.org/core-2.2.0/Array.html#method-i-flatten [[0],[67],[4]].flatten == [0,67,4]
I'm not sure if I understood You correctly. If you want to get index of the smalleest integer in the array You can simply sort it. array=[2,9,90,345] array.sort => [2, 9, 90, 345] In this case the lowest integer would have always an index=0 When you have array=[2,3,4] it is already numeric: array[0].class => Fixnum
Trouble using bsearch with an array of strings
I am getting some confusing behaviour trying to use the c builtin bsearch on an array of strings in C. Here is the code. I know you can use the builtin strcmp for searching arrays of strings, but I included myStrCmp for debugging purposes because I didn't know why it wasn't working. const char *stateNames[] = {"Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "Washington DC", "West Virginia", "Wisconsin", "Wyoming"}; int myStrCmp(const void *s1, const void *s2) { printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, (char *)s1, s2, (char *)s2); return strcmp(s1, s2); } int determineState(char *state) { printf("state: %s\n", state); for(int i = 0; i < 51; i++) printf("stateNames[%i](%p): %s\n", i, &(stateNames[i]), stateNames[i]); char *found = (char *) bsearch(state, stateNames, 51, sizeof(char *), myStrCmp ); if(found == NULL) return -1; return 0; } and here is some of the output when this function is called to look for Alabama. stateNames[0](0x618440): Alabama stateNames[1](0x618448): Alaska stateNames[2](0x618450): Arizona ... stateNames[24](0x618500): Missouri stateNames[25](0x618508): Montana stateNames[26](0x618510): Nebraska stateNames[27](0x618518): Nevada stateNames[28](0x618520): New Hampshire stateNames[29](0x618528): New Jersey stateNames[30](0x618530): New Mexico stateNames[31](0x618538): New York stateNames[32](0x618540): North Carolina stateNames[33](0x618548): North Dakota stateNames[34](0x618550): Ohio stateNames[35](0x618558): Oklahoma stateNames[36](0x618560): Oregon stateNames[37](0x618568): Pennsylvania stateNames[38](0x618570): Rhode Island stateNames[39](0x618578): South Carolina stateNames[40](0x618580): South Dakota stateNames[41](0x618588): Tennessee stateNames[42](0x618590): Texas stateNames[43](0x618598): Utah stateNames[44](0x6185a0): Vermont stateNames[45](0x6185a8): Virginia stateNames[46](0x6185b0): Washington stateNames[47](0x6185b8): Washington DC stateNames[48](0x6185c0): West Virginia stateNames[49](0x6185c8): Wisconsin stateNames[50](0x6185d0): Wyoming myStrCmp: s1(0x415430): Alabama, s2(0x618508): UA myStrCmp: s1(0x415430): Alabama, s2(0x618570): A myStrCmp: s1(0x415430): Alabama, s2(0x618540): PUA myStrCmp: s1(0x415430): Alabama, s2(0x618528): 1UA myStrCmp: s1(0x415430): Alabama, s2(0x618538): GUA myStrCmp: s1(0x415430): Alabama, s2(0x618530): <UA As you can see, the locations visited by bsearch in the course of its search should have valid strings (as was just checked before calling bsearch), but the output if you try to print the char * at that location is garbage. Can anyone see my mistake? Incidentally I get the same bad behaviour (but don't get to follow it as closely obviously) when I call bsearch with the final parameter set to: (int(*)(const void*, const void*))strcmp Thanks!
Since you are using an array of const char *, bsearch() will pass to the comparison function a pointer to those elements. In other words, it will receive const char * const * in its second argument. int myStrCmp(const void *s1, const void *s2) { const char *key = s1; const char * const *arg = s2; printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, key, s2, *arg); return strcmp(key, *arg); }
Your state name (or key) needs to be a pointer to a pointer. Didn't have to add/remove constanywhere. myStrCmpneeds to dereference by one to compare the strings. The code below does what you want I think. Please let me know if not, thanks. #include <stdio.h> #include <stdlib.h> #include <string.h> const char *stateNames[] = {"Alabama", "Alaska", "Arizona", "Arkansas","California", "Colorado", "Connecticut", "Delaware", "Florida","Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "Washington DC", "West Virginia", "Wisconsin", "Wyoming"}; int myStrCmp(const void *s1, const void *s2) { printf("myStrCmp: s1(%p): %s, s2(%p): %s\n", s1, *(char **)s1, s2, *(char**)s2); return strcmp(*(char **) s1, *(char **) s2); } int determineState(char *state) { printf("state: %s\n", state); for(int i = 0; i < 51; i++) printf("stateNames[%i](%p): %s\n", i, &(stateNames[i]), stateNames[i]); char **found = (char **) bsearch(&state, stateNames, 51, sizeof(char *), myStrCmp ); if(found == NULL){ return -1; } else { printf("Found it!: %s\n", *found); } return 0; } int main(int argc, const char * argv[]) { determineState("Alabama"); }