12nm
12nm

Reputation: 41

Modify values of a string in c

I am trying to change the characters in a string using a for loop, here is my code:

#include <stdio.h>

int main(){
char h[] = "ABCDEFGH";
printf("h : %s\n", h);
int i = 0;
for(i; i<sizeof(h)-1; i++){
    printf("i : %i\n", i);
    printf("Starting value : %d\n", h[i]);
    h[i] = "A";
    printf("Test replace h[%u] : %d\n", i, h[i]);
}
printf("Final product : %s\n", h);
}

Here is my output:

h : ABCDEFGH
i : 0
Starting value : 65
Test replace h[0] : 117
i : 1
Starting value : 66
Test replace h[1] : 117
i : 2
Starting value : 67
Test replace h[2] : 117
i : 3
Starting value : 68
Test replace h[3] : 117
i : 4
Starting value : 69
Test replace h[4] : 117
i : 5
Starting value : 70
Test replace h[5] : 117
i : 6
Starting value : 71
Test replace h[6] : 117
i : 7
Starting value : 72
Test replace h[7] : 117
Final product : uuuuuuuu

Why are the values at each index integers (forcing me to use %d instead of %s)? What do those numbers represent? Why is the final product "uuuuuuuu" instead of "AAAAAAAA"? and how can I change the code to do what I am trying to do?

Upvotes: 1

Views: 87

Answers (2)

unwind
unwind

Reputation: 399803

You are confusing strings (double quotes, which are 0-terminated arrays of characters represented as pointers to the first character) with characters (single quotes, which are small integers).

This:

h[i] = "A";

should have given you a serious compiler warning. You should enable and check all warnings.

It should be:

h[i] = 'A';

to assign a new character value. What your code does is take the address of the constant string "A" (remember: double quotes are strings) and smash that into the single character h[i]. The result is unpredictable.

Single characters are printed either as themselves with %c, or as integers with e.g. %d:

printf("on this machine, 'A' is %d\n", 'A');

The above will print 65 on many current-day computers, since the character encoding value used to represent the letter 'A' is 65 in ASCII and Unicode.

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 310950

The type of an element of array h is char while the type of string literal "A" is char[2]. That is string literals are character arrays. When the name of an array is used in expressions it is converted to a pointer to its first element. So your program has undefined behaviour because an object of type char can not represent the value of pointer,

You could use character literal 'A' instead of the string literal "A". For example

h[i] = 'A';

Or you could use the string literal but take only one its element. For example

h[i] = "A"[0];

or

h[i] = *"A";

Upvotes: 1

Related Questions