How to print a char array in C through printf? - Stack Overflow
c - I can't print char array's elements with for loop - Stack Overflow
C - print array of char * - Stack Overflow
c - Printing an array of characters - Stack Overflow
Videos
i want to be able to print out multiple values from an array without having to re-write the char name and array number multiple times, is this possible? example...
char letters[] = {'a','b','c','d'};
printf("%c%c%c%c", letters[0], letters[1], letters[2]);i want to make that code cleaner and easier to use/understand. I thought i'd be able to use
printf("%c", letters[0][1][2]);or seperated by commas, but that doesn't work either. Any suggestions?
The code posted is incorrect: a_static and b_static should be defined as arrays.
There are two ways to correct the code:
you can add null terminators to make these arrays proper C strings:
#include <stdio.h> int main(void) { char a_static[] = { 'q', 'w', 'e', 'r', '\0' }; char b_static[] = { 'a', 's', 'd', 'f', '\0' }; printf("value of a_static: %s\n", a_static); printf("value of b_static: %s\n", b_static); return 0; }Alternately,
printfcan print the contents of an array that is not null terminated using the precision field:#include <stdio.h> int main(void) { char a_static[] = { 'q', 'w', 'e', 'r' }; char b_static[] = { 'a', 's', 'd', 'f' }; printf("value of a_static: %.4s\n", a_static); printf("value of b_static: %.*s\n", (int)sizeof(b_static), b_static); return 0; }The precision given after the
.specifies the maximum number of characters to output from the string. It can be given as a decimal number or as*and provided as anintargument before thecharpointer.
This results in segmentation fault. ? because of the below statement
char a_static = {'q', 'w', 'e', 'r'};
a_static should be char array to hold multiple characters. make it like
char a_static[] = {'q', 'w', 'e', 'r','\0'}; /* add null terminator at end of array */
Similarly for b_static
char b_static[] = {'a', 's', 'd', 'f','\0'};
Take a look at description of getline, which tells that it'll only allocate buffer if line passed is NULL. It'll only be NULL the first time and consequently will reuse the buffer or increase it if line doesn't fit.
If you want it to allocate separate buffers for every word, do
printf("%s", line);
words[count] =(unsigned char*) line;
line = NULL;
count++;
and remove the
if (line)
free(line);
but don't forget to free all non-NULL entries of words somewhere later on.
All pointers in your array are getting set to the same char * (line) which is getting overwritten every iteration in the loop leaving you with an array of char pointers that has the same pointer in each index of the array and that pointer points to a location in memory that has been written over and over until you overwrite it with the last item in the dictionary. To do this the way you are wanting to line would need to use a different char * for each iteration in your loop.
You declare an array of characters like so:
char foo[size];
You seem to have it mixed up with char *, which is a pointer to a character. You could say
char *bar = foo;
which would make bar point to the contents of foo. (Or, actually, to the first character of foo.)
To then print the contents of the array, you can do one of the following:
// either print directly from foo:
printf("%s", foo);
// or print through bar:
printf("%s", bar);
Note, however, that C performs no initialization of the contents of variables, so unless you specifically set the contents to something, you'll get garbage. In addition, if that garbage doesn't happen to contain a \0; that is, a char with value 0, it will keep on outputting past the end of the array.
Your array is not initialized, and also you have an array of pointers, instead of an array of char's. It should be char* array = (char*)malloc(sizeof(char)*size);, if you want an array of char's. Now you have a pointer to the first element of the array.
You got to understand behavior behind your program. So when you load your program it is given N bytes in memory and that N bytes gets reused many times and not erased. So in first instance your program have loaded some data into spot where s[0] would later reside, where as in second something was loaded where s[2] as well. That is why you are getting different output in these 2 cases.
So to sum it up: Your array is not initiated to 0 or unless you do it your self, it is given memory that have been previously used by the same program. To do it as it was pointed before you have to do this:
char s[10] = " ";
....
One more thing I see is you were not expecting space before a, in C/C++/Java array indexes start at 0. So if you do:
char s[4];
s[1] = 'a';
s[2] = 'b';
s[3] = '\0';
print ("%s", s);
you would probably get:
@ab
@ comes up because there was nothing written by you as programmer in memory spot where s[0] resides.
Note that every time you have string in C you have to terminate it with '\0' character.
The problem is that you didn't initialise your array. In order to get that output you can do it in this way:
char s[10];
for(int i=0;i<10;i++)
{
s[i] = ' ';
}
s[1]='a';
s[6]='4';
for(int i=0;i<10;i++)
printf("%c",s[i]);
Don't you need to end your strings with \0 in C? ) For example:
char array[randSize + 1];
for (i=0; i < randSize; i++)
array[i] = 'x';
array[i] = '\0';
(updated this because you indeed probably wanted to get a useful part of string of randSize length).
printf("%s | ", bar);
The %s conversion requires a pointer to a 0-terminated character array, but your array is not 0-terminated. Thus the behaviour is undefined, but what usually happens is that printf continues reading and printing characters until it finds a 0 byte or reaches forbidden memory, causing a segmentation fault, whichever happens first.
Given that the code is really simple, I see mostly coding style issues with it.
Instead of this:
char *names[] = { "John", "Mona", "Lisa", "Frank" };
I would prefer either of these writing styles:
char *names[] = { "John", "Mona", "Lisa", "Frank" };
// or
char *names[] = {
"John",
"Mona",
"Lisa",
"Frank"
};
The pNames variable is pointless. You could just use names.
Instead of the while loop, a for loop would be more natural.
This maybe a matter of taste,
but I don't think the Hungarian notation like *pArr is great.
And in any case you are using this pointer to step over character by character,
so "Arr" is hardly a good name.
I'd for go for pos instead. Or even just p.
You should declare variables in the smallest scope where they are used.
For example *pos would be best declared inside the for loop.
In C99 and above, the loop variable can be declared directly in the for statement.
The last return statement is unnecessary.
The compiler will insert it automatically and make the main method return with 0 (= success).
Putting it together:
int main(int argc, char *argv[])
{
char *names[] = { "John", "Mona", "Lisa", "Frank" };
for (int i = 0; i < 4; ++i) {
char *pos = names[i];
while (*pos != '\0') {
printf("%c\n", *(pos++));
}
printf("\n");
}
}
Actually it would be more interesting to use argc and argv for something:
int main(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i) {
char *pos = argv[i];
while (*pos != '\0') {
printf("%c\n", *(pos++));
}
printf("\n");
}
}
Other points not already mentioned:
Use const where possible
It's better to use const where possible so that it's clear when you are intending to modify things and clear when you're not. This helps the compiler help you find bugs early.
Avoid magic numbers
It's better to avoid having numbers like 4 in the program. If you want to change things later, you may well be left wondering "why 4? what does that mean?" Better would be to assign a constant with a meaningful name.
Use putchar rather than printf for single characters
The printf function is very useful, but putchar is often better suited for single-character output. The reason is that printf has to, at runtime, parse the format string, apply the arguments and then emit the results, while putchar only has to pass a character directly to the output. This particular code isn't exactly performance-critical but it's useful to acquire good coding habits from the beginning.
Use C idioms
It's more idiomatic C to have a loop like this for the characters:
while(*pArr) { /* ... */ }
rather than this:
while(*pArr != '\0') { /* ... */ }
Consider using a "sentinel" value for the end of a list
There are two common ways to iterate through a list in C. One is as you already have it, when you know how many values are in the list. The other way is to use a "sentinel" value -- some unique value that tells the program "this is the end of the list." For a list of names such as this program has, a rational choice for a sentinel value would be NULL.
Omit the return 0 from the end of main
Uniquely for main, if the program gets to the end of the function, it automatically does the equivalent of return 0 at the end, so you can (and should) omit it.
Result
Using all of these suggestions, one possible rewrite might look like this:
#include <stdio.h>
int main()
{
const char *names[] = { "John", "Mona", "Lisa", "Frank", NULL };
for (int i=0; names[i]; ++i) {
const char *ch = names[i];
while(*ch) {
putchar(*ch++);
putchar('\n');
}
putchar('\n');
}
}
You should use %c format to print characters in C. You are using %s, which requires to use pointer to the string, but in your case you are providing integer instead of pointer.
The below will work. You pass in the pointer to a string when using the token %s in printf.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int len = strlen(argv[1]);
char *d = malloc (strlen(argv[1])+1);
strcpy(d,argv[1]);
printf("Value: %s\n", d);
return 0;
}