Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array compilation errors 1

Status
Not open for further replies.

BigxRed

Technical User
Jan 5, 2011
4
US
hello, i am currently trying to accommodate myself with the c language. i have been trying to learn by reading "C: The Programming Language" by Kernighan and Ritchie (typically referred to as the "White Bible"). I have been trying to write-up some code of my own that consists of the following:

main(){
int i;
i = 0;

char sarray [17];
sarray = "This is a string!";

while (i != '\0')
printf("sarray");
printf("\n");
}

however, whenever i try to run gcc (I have been doing all of my coding on an Ubuntu machine), I am given errors with this line:

sarray = "This is a string!";

what is the problem? The error message states:

incompatible types when assigning to type ‘char[17]’ from type ‘char *’

how do I resolve this issue? Any help would be greatly appreciated!
 
To assign strings, use strcpy
Code:
strcpy (sarray, "This is a string");
 
Thanks Ritchie, arrays in C are very amusing objects. On the one hand an array is a simple collection of contiguous elements numbered from 0 to array size - 1. On the other hand an array name implicitly converted to the pointer to the first array element in all contexts (except argument of sizeof and unary & operators). Yet another thing: it's impossible to modify this pointer value.

The type of text literals is a pointer to char allocated in constant memory (never try to modify this memory via this pointer).

So in expression (assignment) statement
Code:
sarray = "This is a string";
you are trying to assign a pointer value (right side: const char* type) to the non-modifiable pointer value (left side: array name is converted to a pointer).

Reread the C language Bible. Try to understand C arrays once and for all.

It's interesting that you can modify your code snippet:
Code:
char sarray[17] = "This is a string";
It's OK, but it's not assignment: it's a special form of array initialization (see K&R again).

Good luck!
 
You also have a problem with your "[tt]while[/tt]" loop. Your test isn't quite right, and you never increment "[tt]i[/tt]", so it's an infinite loop. Also your "[tt]printf[/tt]" isn't right so you will just be printing "[tt]sarraysarraysarray...[/tt]" forever.

I won't suggest code to you since you're learning. It's good exercise to learn how to fix these things yourself.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top