Friday, July 31, 2009

Why doesn't this work in C?

This is in C NOT c++





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





struct city {


char name[50];


double x;


double y;


};


/* array structure for cities */


struct city cities[100];





char line[100];


int main()


{


char test[7] = "Teasdf";


char *test_ptr;


test_ptr = %26amp;test;


cities[0].name[50] = *test_ptr;


printf("test: %s\n", cities[0].name[50]);





}











Get's this compile error:


[Warning] assignment from incompatible pointer type

Why doesn't this work in C?
char test[7] makes the variable "test" a "char *".


Therefore use "test_ptr = test".


Also to copy the string into city name use strncpy().
Reply:which compiler did you use? I compiled it with gcc and had to make some changes. You have several pointer problems...





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;string.h%26gt;





struct city


{


char name[50];


double x;


double y;


};


/* array structure for cities */


struct city cities[100];





char line[100];


int main()


{


char test[7] = "Teasdf";


char *test_ptr;


test_ptr = test;


strcpy(%26amp;(cities[0].name[0]), test_ptr);


printf("test: %s\n", cities[0].name);


}
Reply:this is a virus code you need to get it off your computer now!! just clean your disk and that should do it.


No comments:

Post a Comment