Jump to content

Help please

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Wolfgang

Wolfgang

    Newbie

  • Members
  • Pip
  • 3 posts
Hi, i don't know so well how to work with realloc... and i have a problem in this function:

#include <stdio.h>
#include <stdlib.h>

int main(){

char *tmp = "Mauro Silva";

tmp = (char *)realloc(tmp, 5*sizeof(char));

printf("%s", tmp);


return 0;
}


why is it??

#2
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
realloc is used when you want to re-allocate stuff, after you've allocated already, using f.ex. malloc. In your example you should use, malloc, not realloc.

Take a look at this:
#include <stdio.h>

int main()
{
	char *myBytes;
	
	// Allocate five bytes for "myBytes"
	myBytes = (char *)malloc(5 * sizeof(char));
	
	// Now we want to re-allocate two bytes
	myBytes = (char *)realloc(myBytes, 2 * sizeof(char));
	
	return 0;
}


#3
Wolfgang

Wolfgang

    Newbie

  • Members
  • Pip
  • 3 posts
well what i actually wanna do is to get this function to work:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct node *link;

struct node{
char *name;
link next;
};

int getfilenames(link lst){

char *tmp = (char *)malloc(80*sizeof(char));
int i;

while (1){
scanf("%s", tmp);
printf("%s\n", tmp);

if(strcmp("FILES", tmp)==0) break;
}

while (1){
link tmplst;

scanf("%s", tmp);
printf("%s\n", tmp);

if(strcmp("FILES", tmp)==0) break;
}

while (1){
link tmplst;

scanf("%s", tmp);
printf("%s\n", tmp);

if(strcmp("END", tmp)==0) break;

tmplst = malloc(sizeof(struct node));

tmplst->name = tmp;
tmplst->next = lst;
lst = tmplst;

i++;
}

return i;

}

#4
v0id

v0id

    Retired

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,936 posts
What should the function do?
There's no trouble in compiling it, and no trouble in using it.

But to me it looks strange, why all those while-loops?

#5
Wolfgang

Wolfgang

    Newbie

  • Members
  • Pip
  • 3 posts
well the function is supposed to wait until it gets the word: FILES and then its supposed to save the strings that come next in a list (which is the argument of the function)... until the word END appears... like:

FILES
a.txt
b.txt
c.txt
END

and the int i is supposed to return the number of files... in this case 3...

Already seen the problem... XD
Noob mistake... =P

Thanks for the help anyway... ;)