Hello. :)
This is my first post and it's unfortunately to ask for help.

The problem is as follows:

  • The user types in how many names they wish to enter.
  • An array must be able to hold this many names.
  • The user then types the names.
  • Any characters over the limit are ignored, and the rest of the string is copied into the array.

I have been trying for the past hour or so to get this working and any hints in the right direction would be excellent.

I've deleted so much code that I'm basically left with nothing working. Originally, I tried using calloc for the array.
Then I tried this:

char str[numChar];
	
printf("How many names will you be entering?\n");
scanf("%i", &numNames);
		
charArray = (char*) malloc(sizeof(str));//creates 2D array for names

I'm not sure if I've made any progress since I started. :(

Originally it looked as shown:

//char or char*??
	charArray = (char) calloc(numNames, numChar);//creates 2D array
	
	if(charArray == NULL)
	{
		printf("Program error.");
		exit(0);
	}

	//get each name
	c = 0;
	for(i = 0; i < numNames; i++)
	{
		printf("\nEnter name %i: ", &i);		
		
		for()//until final character is reached
		{
			*charArray = fgetc(stdin);//get char from keyboard
			c++;	
		}

		if(i < numNames - 1)//if not on last name
			charArray += numChar - c;//point to start of next name
		else
			charArray -= c;//move to start of last name
	}

I would appreciate any help.

Comments
Nicely written post on first try. And thanks for using code tags :)

What you need is an array of character pointers. When you enter the number of strings then allocate that many character pointers

char** array = 0;
int numNames = 0;
printf("How many names will you be entering?\n");
scanf("%i", &numNames);
if( numNames > 0)
{
    array = malloc(numNames * sizeof(char*));
}

Now when you enter each of the names

int i;
char name[80];
for(i = 0; i < numNames; i++)
{
    printf("Enter a name\n");
    fgets(name, sizeof(name), stdin);
    if( name[strlen(name)-1] == '\n')
        name[strlen(name)-1] = 0;
    array[i] = malloc( strlen(name) + 1 );
    strapy(array[i], name);

Thank you very much. :)
I'm having a problem where it ignores the fgets in the first loop iteration but I finally feel like I'm getting somewhere with this.

Thank you very much. :)
I'm having a problem where it ignores the fgets in the first loop iteration but I finally feel like I'm getting somewhere with this.

That's because you didn't clean up after this:

scanf("%i", &numNames);

The newline is left over.

I caught that a few minutes after posting but didn't want to double post.
I figured out that the newline was being passed into the fgets so I caught it with another function call. :)

Also, I just finished the rest of the exercises, so thanks again!

This article has been dead for over six months. Start a new discussion instead.