Hi,

I am working on structures. One of the structure member is char array i.e string. When I assign another string to this then it throws the incompatible error. The code is the follwing. The problem line is commented.

Code:

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

struct file_data{

	char src_ip[18];
	char dst_ip[18];
	char src_port[8];
	char dst_port[8];
	char p2p_proto[18];

};


typedef struct file_data data;

	void readdata();

int main(){

	
	readdata();
	printf("The program is working\n");
	return 0;
}

void readdata(){

	data getdata;
	FILE *fp;
	char input[18];
	int i=0;

	//getdata=(data *)malloc(sizeof(data));	
	input=malloc(18);	
	fp=fopen("pktfile.txt","r");

	while(fgets(input,18,fp)!=NULL){

	if(i==0){
		
               //Problem Section of code
		getdata.src_ip=input;
		i++;
	}
	else if(i==1){
		
		//getdata->dst_ip=input;
		printf("%s",input);
		i++;
	}
	else if(i==2){
		
		//getdata->src_port=input;
		i++;
	}
	else if(i==3){
		
		//getdata->dst_port=input;
		i++;
	}
	else if(i==4){
		
		//getdata->p2p_proto=input;
		
		i=0;
		//bzero(getdata,sizeof(getdata));
	}
		
	else{
		
		printf("Wrong File");
		break;
	}

	//printf("%s",input);
	}
	fclose(fp);
}

Thanks in advance

You cannot directly use the assignment operator when dealing with C strings. Use strcpy instead.

line 44 for example should be:

strcpy(getdata.src_ip, input);

line 36 also returns an error. You can omit this line because array "input" has been previously declared as a character array which is of size 18 bytes. But if you insist on using malloc:

First, declare "input" on line 32 as,

char * input;

Then, on line 36, perform the malloc operation,

input = (char *) malloc(18);

The type of pointer returned by malloc is always of type (void *), so you need to perform a cast operation to the desired data type of data pointer. malloc returns a pointer to a memory block allocated by the function. Therefore, the left side of the assignment must also be of pointer type.

Edited 6 Years Ago by angzie: additional info

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