-1

So basically I don't know how to work with this command well, I searched around the forums and could understand how to print the string and using the pointers but I want to divide the string and save all the tokens in different variables.

I'm trying to do something like this

char s[20],*pt,name[10];
pt=strtok(s," ");

Now I want to save the first toke on the name string, but I get errors on the terminal and the only thing that works (passing only the pointer) gets me 1 letter only.

  • name=pt; doesnt work.
  • *(name)=*pt works but gets me only 1 letter.

The complete code

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

int main(){
FILE *f=fopen("tarefas.txt","r");
char s[50];

typedef struct{
char nome[20];
int trab;
int acab;
} tarefa;


int i=0,*dias;
tarefa *v;
char *pt;

v=(tarefa *) malloc(sizeof(tarefa));
dias=(int *) malloc(sizeof(int));


while(fgets(s,50,f)){
pt= strtok(s," ");

v[i].nome=s; //doesnt work

int t=strlen(v[i].nome);
v[i].nome[t]='\0';

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

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
João Gomes
  • 81
  • 10

1 Answers1

1

name=pt; doesnt work.

and

v[i].nome=s; //doesnt work

They are not supposed to work, anyway. Array names are not modifiable lvaues and hence are not assignable in C.

To copy a string, you should be using strcpy().

Something like

 strcpy(v[i].nome,s);

should do the job just fine.

That said, you should check

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261