Why don't work?

Hi everyone,

I'm try to learn C language, but am having trouble. Look at this code, why it does not work?

It was to enroll 5 books and then print the five books registered, but all results are equal.

Help me please.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>

int cadastra(char * nome, int ordem);

int seq;
char * livro[10];

int main()
{
	char nome[100];
	int i;
	
	seq = 0;
	
	for (i = 0; i < 5; i++) {
		printf("Digite o nome do livro: ");
		fgets(nome, 100, stdin);
		cadastra(nome,i);
	}
	
	printf("\nListando os livros cadastrados.\n");
	
	for (i = 0; i < 5; i++)	{
		printf("%d - %s", i, livro[i]);
	}
	
	return 0;
}

int cadastra(char * nome, int ordem)
{
	livro[ordem] = nome;
	return 0;
}

Hi.
After translating
I found that the problem was you had not allocated room for the book names
and also livro[ordem] = nome only copies the pointer which is why all your results were the same.

by changing
1
2
3
4
5
int cadastra(char * nome, int ordem)
{
	livro[ordem] = nome;
	return 0;
}


to
1
2
3
4
5
6
7
8
int cadastra(char * nome, int ordem)
{
	livro[ordem] = new char[strlen(nome)+1];
	
	memcpy(livro[ordem],nome,strlen(nome)+1);
	
	return 0;
}


which allocates space and then copies the string

you will also need to add this to your includes

 
#include <string.h> 


Hope this helps
Shredded
livro must be a 2D array to store strings:

char livro[10][100]; // store 10 strings of max length of 100 chars

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <stdio.h>
#include <string.h>

int cadastra(char * nome, int ordem);

int seq;
char  livro[10][100]; // You need 2-dimensional array to store array of strings

int main()
{
	char nome[100];
	int i;

	seq = 0;

	for (i = 0; i < 5; i++) {
		printf("Digite o nome do livro: ");
		fgets(nome, 100, stdin);
		cadastra(nome,i);
	}

	printf("\nListando os livros cadastrados.\n");

	for (i = 0; i < 5; i++)	{
		printf("%d - %s", i, livro[i]);
	}

	return 0;
}

int cadastra(char * nome, int ordem)
{
  // Yo can't use = to assign C-style strings, you must use strcpy
	strcpy(livro[ordem],nome); 
	return 0;
}


http://www.cplusplus.com/doc/tutorial/
http://www.cplusplus.com/doc/tutorial/arrays/
http://www.cplusplus.com/strcpy

EDIT: too slow
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
int seq;
char *livro[10];
void cadastra(char * nome, int ordem)
{

	livro[ordem] = (char *)malloc(strlen(nome) + 1);
	strcpy(livro[ordem], nome);
}




int main()
{
	char nome[100];
	int i;
	
	seq = 0;
	
	for (i = 0; i < 5; i++) {
		printf("Digite o nome do livro: ");
		fgets(nome, 100, stdin);
		cadastra(nome,i);
	}
	
	printf("\nListando os livros cadastrados.\n");
	
	
	for (i = 0; i < 5; i++)	{

		printf("%d - %s", i, livro[i]);
	}
	
	return 0;
}
Topic archived. No new replies allowed.