-
C string question
Hi, I recently started learning programming in C, I am not a programming newbie, just new to C, now here is my question:
I am experimenting with strings, because they work in an entirely different way from what I am used to, this is what i did
Code:
int teller;
int aantal = 3;
int getal[aantal];
int *ptr;
ptr = &getal[0];
*ptr = 1;
ptr = &getal[1];
*ptr = 2;
ptr = &getal[2];
*ptr = 3;
this is not my problem, the problem is when I try to output the string, i found a way around the problem using this:
Code:
for (teller = 0; teller <= (aantal-1); teller++)
{
ptr = &getal[teller];
printf("%d",*ptr);
}
but I believer there is a better way to output it, but I can't seem to find it, I always get an error during compiling like "format '%s expects type 'char *' but argument 2 has type 'int *'
any help?
-
That's because a string is a null-terminated array of type char. But you have a simple (not null-terminated) array of type int.
The only string in all of your code is:
-
You can simplify the loop somewhat like this -- incremting the pointer on each loop interation instead of reseting it to some other value.
Code:
int* ptr = getal;
for (teller = 0; teller < aantal; teller++)
{
printf("%d",*ptr++);
}
-
ok, it's not a string, but still, if I try to ouput "geheel" the normal way:
Code:
printf("%d",getal);
the compiler says:
"format '%d expects type 'int' but argument 2 has type 'int *'"
-
your compiler is right! see my previos post for the right solution. You can't use character array solution to output int arrays.
-
My original idea was trying to modify one element of a character string, but since that didn't seem to work out, I first tried this, now, then, can you tell me how to change an element of a string?
f.e. if i do this
Code:
char word[3] = "foo";
and I wanted to change the "f" into a "b", how do I do this?
-
way #1:
way #2
Please note though that your declaration is incorrect. You're making an array of 3 elements but storing 4 characters in it. "foo" in memory is actually 'f', 'o', 'o', '\0'. Every string in C must end with the value 0.
So your char word[3] = "foo"; is actually equivalent to char word[3] = { 'f', 'o', 'o', '\0' }; See the problem?
-
yes, i see the problem, it's a common made mistake for c newbies, I've read it on several sites, I hope I won't forget the null terminator in the future
hmm, this shows that I've got much to learn, I tried that, but always used " instead of '
thanks for the help
-
define it as below and the compiler will figure it out for you. That way you can create very large strings without counting up the number of characters -- compilers are good at doing that.
Code:
char word[] = "foo";