I have a program that is supposed to take an unknown number of strings from a user. It supposed to check and see if a string has already been entered so that there will be no duplicates in the dynamic array.
The problem is that I can't get the program to recognize when an array slot has nothing in it. I've used both NULL and nullptr and neither works. What's more is even though I haven't fully initialized the array, there's still something in the location.
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "new"
int _tmain(int argc, _TCHAR* argv[])
{
//Variables
int i=0,end=0,requiresSize=1;
char ** temp;
char item[256]="a";
char ** requires;
//Requires is initialized as an array, but the individiual slots are not
requires = new char * [requiresSize];
while(strcmp(item,"q-")){
end=0;
printf("Enter h- for help.\nEnter q- to quit.\n");
printf("Please enter a string\n");
gets_s(item);
printf("%s\n",item);
if(!strcmp(item,"h-")){
printf("Enter a string to add to the list.\nEnter p- to print the list.\n");
end=1;
}
if(!strcmp(item,"q-")){
break;
}
if(!strcmp(item,"p-")){
if(requires[0]!=nullptr){
for(int j=0;j<requiresSize;j++){
printf("%d. %s\n",j,&requires[j]);
}
}
end=1;
}
while(end==0){
//if search index is larger than size of the array,reallocate the array
if(i>= requiresSize){
temp = new char * [requiresSize*2];
//Initialize each element in temp
for(int j=0;j<requiresSize*2;j++){
temp[j]= new char[256];
}
for(int j =0;j<requiresSize;j++){
//for each element in requires, copy that element to temp
strncpy_s(temp[j],_TRUNCATE,requires[j],_TRUNCATE);
}
delete *requires;
requires = temp;
requiresSize = requiresSize *2;
}
//if the index at requires is not empty, check to see if it is the same as given item
if(requires[i]!= nullptr){//This should be returning false and preventing the nested if from running, but doesn't
if(!strcmp( item, requires[i])){//runtime error occurs here from trying to access requires[i]
//if they are the same, break out of the loop, item is already included
break;
}else{
//otherwise, increase the index and check again (continue loop)
i++;
break;
}
}else{
//if the index is empty, add the item to the list and break out of loop
requires[i]= new char [256];
strncpy_s(requires[i],_TRUNCATE,item,_TRUNCATE);
break;
}
}
}
delete *temp;
delete requires;
return 0;
}
I can't figure out what I'm missing or put in the wrong place