-
Variables within strings
Hello everyone!
I'm a beginner with C, having learned some basics in a university course, but I want to get better at programming. It's also my first post here :3
Now, on to my question.
I have created a 2d char array which I want to fill by using for functions. They should all have values in the form of "i,j", where i and j are the coordinates of each string in the array (i.e. the first element of the first line should have a value of 1,1).
However, I can't figure out how to make the i and j in the value assignment variable. So, I'm stuck with
Code:
for(i=1; i<=SIZE; i++)
for(j=1; j<=SIZE; j++)
map[i][j]="i,j";
but I don't know what to do to make the last i and j variable, so every element just gets the value "i,j" instead of the correct numbers.
Thanks in advance for any help!
EDIT: I'd also like to be able to read the values I give to each element, aka its coordinates.
-
It would be helpful if you showed us how you declared the 'map' array. Are you sure you wanted it char? Each element should contain what exactly? An integer, a single char, a string? You mentioned that the first element should contain a value of 1,1. Is that a string?
In C array indices are 0 to SIZE-1 so you should be careful with your limits.
-
In C arrays' index number starts with 0 ends with size-1. Let's use your for loop:
Code:
int array[5];
int i;
for(i = 1; i <= 5; i++)
array[i] = 0;
/*Then Print*/
for(i = 1; i <= 5; i++)
printf("%d,", array[i]);
The code above would print "0,0,0,0,0," but the code is wrong. Because you started from 1 you didn't fill array[0] and because you ended at 5 you filled array[5] and that place doesn't belong to your array. Eventho it prints out what you want that last space you put 0 in might belong to something else. You can learn more about this when you learn pointers. Correct code should be this:
Code:
int array[5];
int i;
for(i = 0; i <= 4; i++)
array[i] = 0;
/*Then Print*/
for(i = 0; i <= 4; i++)
printf("%d,", array[i]);
Now this was your first mistake. You second mistake is trying to put 3 characters i , and j into 1 character space. You cannot do that. To solve your problem you can create an integer matrix instead of char and place coordinates without ','.
For example 5x5 matrix might look like this:
00 01 02 03 04
10 11 12 13 14
20 21 22 23 24
30 31 32 33 34
40 41 42 43 44
-
Thank you Vsky, I resorted to do something like you suggested a bit after I posted this question.
Just an fyi though, I should have mentioned that. The SIZE is a constant variable that specifies my desired size of the array, and the array is one row and one column larger, i.e. map[SIZE+1][SIZE+1].
And I just ignore row and column 0.
EDIT: nonoob, yes, "1,1" was supposed to be a string.