Segmentation Fault when trying to populate array of strings in C - arrays

int main() {
const char* text = "the quick brown fox jumps";
int* argc = 0;
char *argv[] = {};
printf("%d", parse_command(text, argc, argv));
}
int parse_command(const char *inp, int *argc, char *argv[]) {
int offset = 0;
int count = 0;
int i = 0;
bool bool1 = true;
while (*(inp + offset) != '\0') {
if (inp[i] == ' ')
bool1 = true;
if (bool1 && inp[i] != ' ') {
bool1 = false;
argv[i] = &inp[i];
++count;
}
++offset;
i++;
}
*argc = count;
return count;
}
I am trying to split the character array inp into words, and return the number of words. What is considered a word is: a sequence of non-blank characters ending in one or more blank spaces. I want argc to be set to the number of words (which I think works fine), and argv[0] should point to the first character of the first word, argv[1] to the first character of the second word, and so on.
I keep getting segmentation fault error. Is this because char* argv[] is empty when initialized? If so, how can I initialize it to a specific length?

When you declare int *argc = 0 you are creating a pointer, and setting its value to 0.
Then dereferencing this pointer is invalid as it is a null pointer, which results in a segfault.
What you can do is create an integer (int argc = 0) and pass it by reference to the function (&argc).

Related

Counting # of index of undefined char array in C

I'm trying to count the number of indexes of an undefined char array which is used as a parameter in the function.
I am already aware that if my array was fixed I can use "sizeof", which isn't the case here.
Attempt:
int counting(char *name3) {
int count = 0;
int i;
//I have no idea what to put as my condition nor do I believe
//I am approaching this situation correctly...
for (i = 0; i < sizeof(name3); i++) {
if (name3[i] != '\0') {
count++;
}
}
return count;
}
Then if it is run by the following code
int main(void) {
char *name = "Lovely";
int x = counting(name);
printf ("The value of x = %d", x);
Prints: The value of x = 0
Any help or pointers would be amazing. Thank you in advance.
In C, Every string ends with '\0' (Null Character)
You can iterate until you meet the Null Character
The example code would be like this
char* name = "Some Name";
int len = 0;
while (name[len] != '\0') {
len++;
}
Also, if it is a char pointer, not char array, sizeof(char*) will always return 4 in 32-bit application and return 8 in 64-bit application (the size of the 'pointer' itself - the memory address size)
#include <stdio.h>
int main()
{
int i=0;
char *name = "pritesh";
for(i=0;;i++)
{
if(name[i] == '\0')
{
break;
}
}
printf("%d", i);
return 0;
}
This should work
note: this might be syntactically incorrect as I have not had my hands on c since a long time

Why is my pointer disappearing?

I have a class that is meant to return a char** by splitting one char* into sentences. I can allocate the memory and give it values at a certain point, but by the time I try to return it, it's completely missing.
char **makeSentences(char *chapter, int *nSentences){
int num = *nSentences;
char* chap = chapter;
char **sentences;
sentences = (char**) malloc(sizeof(char*) * num);
int stops[num + 1];
stops[0] = 0;
int counter = 0;
int stop = 1;
while (chap[counter] != '\0'){
if (chap[counter] == '.'){
stops[stop] = counter + 1;
printf("Place: %d\nStop Number: %d\n\n", counter, stop);
stop++;
}
counter++;
}
for (int i = 0; i < num; i++){
int length = stops[i+1] - stops[i];
char characters[length+1];
memcpy(characters, &chap[stops[i]], length);
characters[length] = '\0';
char *sentence = characters;
sentences[i] = sentence;
printf("%s\n",sentence);
printf("%s\n", sentences[i]);
}
char* testChar = sentences[0];
printf("%s\n", sentences[0]);
printf("%s]n", testChar);
return sentences;
}
The last two printing lines don't print anything but a newline, while the exact same lines (in the for loop) print as expected. What is going on here?
The problem is these three lines:
char characters[length+1];
char *sentence = characters;
sentences[i] = sentence;
Here you save a pointer to a local variable. That variable characters will go out of scope every iteration of the loop, leaving you with an "array" of stray pointers.
While not standard in C, almost all systems have a strdup function whichg duplicates a string by calling malloc and strcpy. I suggest you use it (or implement your own).

A simple C exercise going wrong: Trying to return a pointer to an array of two strings

"Return a pointer to an array of two strings. The first is the characters
of string s that are at even indices and the second is the characters from
s that are at odd indices"
char **parity_strings(const char *s) {
char** parity = malloc(sizeof(char*) * 2);
char even_strings[] = "";
char odd_strings[] = "";
int x = 0;
int y = 0;
for (int i = 0; i < strlen(s); i++) {
if ((i % 2) == 0) {
even_strings[x] = s[i];
x++;
}
else {
odd_strings[y] = s[i];
y++;
}
}
parity[0] = even_strings;
parity[1] = odd_strings;
return parity;
}
int main(int argc, char **argv) {
char **r = parity_strings(argv[1]);
printf("%s %s %s", r[0], r[1], argv[1]);
return 0;
}
My logic makes sense but the output is always incorrect. For example, with input ababab I get back ababab while the expected output is aaa bbb ababab. What did I do wrong?
The string named even_strings is a local variable, so its memory will be freed after your function returns, so it is not valid to try to return a pointer to it to the caller.
Try changing this line:
char even_strings[] = "";
to something like this:
char * even_strings = malloc(some_size);
The same goes for your odd_strings string.
Also, be sure to pick a good value for some_size so that your program allocates enough memory for each string so that it can hold all the data you are writing to it.
even_strings and odd_strings are arrays of size 1 each. Your code writes out of bounds (even_strings[x] = s[i], odd_strings[y] = s[i]). Furthermore, they're local variables that cease to exist once parity_strings returns, so the returned pointers are garbage.

Initialize string array in C and count number of letters inside

I found this example
int SizeofCharArray(char *phrase)
{
int size = 0;
int value = phrase[size];
while(value != 0)
{
value = phrase[size];
size++;
};
//printf("%i%s", size, "\n");
return size;
}
here
But how can I count number of letters in string array using pure C? Even I do not understand how can I initialize string array?!
Thank you!
The posted code is of rather poor quality. The name of the function, SizeofCharArray, does not match the description, count number of letters in string array.
If you want to return the number of characters in the array, use:
int SizeofCharArray(char *phrase)
{
int size = 0;
char* cp = phrase;
while( *cp != '\0')
{
size++;
cp++;
};
return size;
}
If you want to return the number of letters in the array, use:
int isLetter(char c)
{
return (( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ));
}
int GetNumberOfLetters(char *phrase)
{
int num = 0;
char* cp = phrase;
while( *cp != '\0')
{
if ( isLetter(*cp) )
{
num++;
}
cp++;
};
return num;
}
This will count the number of alphabetic characters in a c-string:
#include <ctype.h>
int numberOfLetters(char *s)
{
int n = 0;
while (*s)
if (isalpha(*s++))
n++;
return n;
}
If you want the actual number of characters, counting characters like spaces and numbers, just use strlen(s) located in string.h.
To find the length of C string, you can use strlen() function
#include<string.h>
char str[]="GJHKL";
const char *str1="hhkjj";
int len1=strlen(str)<<"\n";
int len2=strlen(str1);
It's not particularly good C. I doesn't give you the size of a char array -- that's impossible to determine if you've lost that information. What it does give you is the size of a null-terminated char array (AKA a c-string), and it does so by counting the characters until it finds the null-terminator (0 byte or '\n'). As a matter of fact, what you've got up top is a not particularly good strlen implementation (strlen is a standard library function that does the same thing -- determine the size of a null-terminated char array)
I believe this below should be a little more C-ish implementation of the same thing:
size_t strlen(const char *s){
const char* ptr = s;
for(; *ptr; ++ptr); //move the pointer until you get '\0'
return ptr-s; //return the difference from the original position (=string length;)
}
It returns size_t (64 bit unsigned int if you're on a 64 bit machine and 32 on 32 machines, so it will work on arbitrarily long strings as long as they fit into memory) and it also declares that it won't modify the array it measures (const char *s means a pointer you promise not to use to change what it points to).

C programming find length of 2 Dimensional array

My program grabs command line arguements with argc and argv[]. My question is how can I find the length of argv[1][i].
My code that grabs length of argv[]
int my_strlen(char input[]){
int len = 0;
while(input[len] != '\0'){
++len;
}
return len;
}
but when I try to find argv[1][len] I get a subscripted value is neither array nor pointer:
my attempt
int my_strlen(char input[]){
int len = 0;
while((input[1][len] - '0') != '\0'){
++len;
}
return len;
}
FULL CODE:
#include <stdio.h>
#include <math.h>
int my_strlen(char input[]);
int main(int argc, char *argv[]){
int length = 0;
length = my_strlen(argv[1]);
long numberArr[length];
int i, j;
for(i = 0; i < length; i++){
numberArr[i] = argv[1][i] - '0';
}
return 0;
}
int my_strlen(char input[]){
int len = 0;
while((input[1][len] - '0') != '\0'){
++len;
}
return len;
}
Thanks for any help in advance!
I think you're confused about the argv content. The OS will pass a number of ASCIIZ strings, such that invoking my_program with arguments ala...
my_program first second third
...is similar to having the following declaration in your program...
int argc = 4;
const char* argv[4] = { "my_program", "first", "second", "third" };
Hence, when you index into argv[1][i] you're getting the i-th character in the string "first". That's only valid for values of i between 0 (which yields 'f'), and 5 (which indexes to the terminating NUL character '\0').
So, there no two-dimensional N*M array, but there is an array of pointers-to-(array-of-char). You can invoke the normal strlen() function as in strlen(argv[1]) to find out the number of characters in each argument. Only argc tells you the total number of elements in argv.
Does that help?
In main, you're passing argv[1] to my_strlen. That means my_strlen just receives a normal, single-dimension string. It doesn't need to do input[1][len], just input[len].

Resources