Storing char* array size in an int counter [duplicate] - c

This question already has answers here:
Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]
(6 answers)
Closed 6 years ago.
Well, I have the problem with the data updating in my counter int x. I am passing a lot of char* strings to my function, e.g. when I pass first char* of the length of 8, int x will be 8. Then if I pass the next char* of the length of 11, x still will hold the value of 8. Any advice on fixing it?
bool check(const char* word)
{
char checker[LENGTH+1];
int x = sizeof(word);
for(int a=0; a<x; a++) {
checker[a] = word[a];
}
for(int i=0; i < x-1; i++) {
//check if all chars are lower-case
if(checker[i] < 'a' && checker[i] != '\'') {
checker[i] = tolower(checker[i]);
}
}
}

sizeof(word) is giving you the size of your pointer. Use strlen instead to get the length of the string.
Also a style note, x isn't a great name for a variable that stores a string length, I'd name it something more to do with what it's actually used for.

Related

Why did the array lose the last element when passed into another function? [duplicate]

This question already has answers here:
Why isn't the size of an array parameter the same as within main?
(13 answers)
Closed 1 year ago.
I made an static int arr[3] and set to 1, 2, 3.
I can print 1, 2, 3 in the same function.
But when I pass the array it only prints 1, 2.
Why? What happened? How do I fix this?
#include <stdio.h>
void printArray(int* arr){
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){
printf("%d\n",arr[i]);
}
}
int* makearray()
{
static int arr[3];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
printf("The Array before passing onto stack\n");
size_t n = sizeof(arr)/sizeof(arr[0]);
for(int i=0; i<n; i++){ printf("%d\n",arr[i]);}
printf("\nThe Array when attempting to pass to another function\n");
printArray(arr);
return arr;
}
int main(void) {
int* m = makearray();
return 0;
}
By converting your array to a pointer, you removed the information that sizeof needs to know its total length.
Instead, it just gives you the size of a single int *, which is twice the size of a single int on your machine.
Hence, you only see the first two elements.
In C, you're basically forced to pass around the length alongside the pointer. You can wrap the two in a struct to make it easier to use, but don't expect the niceties of other languages you may be used to.

How can I count the number of elements in my integer array [duplicate]

This question already has answers here:
C sizeof a passed array [duplicate]
(7 answers)
Closed 3 years ago.
I'm programming with the C language and I need to count how many elements are in the array to use further in the program.
Most online answers have arrays with like terms (Ex: 55, 66, 77) but my array will consist of random numbers.
An example of my array would be (4, 6, 77, 450, 0, 99).
The code i'm currently using to count the size is as follows, but the code doesn't work when 0 is an element of the array.
int size = 0;
while(*(arr+size) != '\0'){
size++;
}
And, I also tried to use sizeof but it also doesn't work. See the complete program below.
#define MAX 20
void display(int *arr);
main(int argc, char *argv[]) {
int array[MAX], count;
/* Input MAX values from the keyboard. */
int i; count=0;
while ( scanf("%d", &i) != EOF){
*(array + count) = i; // store in array[count]
count++;
}
/* Call the function and display the return value. */
printf("Inputs: ");
display(array);
return 0;
}
/* display a int array */
void display(int *arr) {
int size = 0;
int s2 = sizeof(arr)/ sizeof(arr[0]);
printf(" -- %d -- ", s2);
while(size <= s2){
printf("%d ", *(arr+size));
size++;
}
}
display is the function that is trying to count the elements in the array. s2 always returns value of 2, which is incorrect.
How can I count the elements of the array?
So, the only hard constraint I have seen stated so far is:
The caller of the function has to tell the function how many elements are in the array.
I'm not allowed to do that, only an integer array is to be given to the function
If this is true, then you will have to use a mechanism that is understood between the caller and the function for how to communicate the number of elements in the array.
One way to achieve this is to reserve one slot in your array to represent the size of the array. Since MAX is global to your program, your function can assume there is a number at MAX that represents the count.
int main () {
int array[MAX+1], count;
//... get input, calculate count ...
array[MAX] = count;
//... use the array ...
}
Now, when you call functions with the array, they can visit array[MAX] to find the size of the array.

How to get a size of char**? [duplicate]

This question already has answers here:
Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]
(6 answers)
Can I know char-array-size to which a char pointer variable points? [duplicate]
(5 answers)
Closed 6 years ago.
I want to count size of my array (how many values/indexes are there).
I've found something like this on StackOverflow
char **sentences;
while ((c = fgetc(fp)) != EOF) {
... fill the array...
}
size_t w = sizeof(sentences); // this is wrong! it returns size of pointer (memory)
It gives me "w = 4" but my array has 6 records.
I need this for "for loop" to print my results (tried to count every loop in "while", but I got it in different function and I don't know to return 2 values in array [count|array of strings]).
I will be happy for any idea how to print the whole array.
You can return your actual count like this:
#include <stdio.h>
#include <stdlib.h>
char **doSomething(size_t *count) {
char **sentences;
// Mock initialization of sentences, please skip :-)
sentences = (char **)calloc(13, sizeof(char *));
for (int i = 0; i < 13; i++) {
sentences[i] = (char *)calloc(8, sizeof(char));
sprintf(sentences[i], "quux-%d", i); // Just filling in some foobar here.
}
// ---------
*count = 13; // <-- Look here, we're dereferencing the pointer first.
return sentences;
}
int main(int argc, char **argv) {
size_t size;
char **res;
// Sending the address of size, so the function can write there.
res = doSomething(&size);
for(size_t i = 0; i < size; i++)
printf("res[%lu]: %s\n", i, res[i]); // You should see the filler outputted to stdout.
return 0;
}

Strange result getting length of array [duplicate]

This question already has answers here:
Why does a C-Array have a wrong sizeof() value when it's passed to a function? [duplicate]
(6 answers)
Closed 9 years ago.
Why does this return a length of 8??
#include <stdio.h>
int getLength(char arr[]) {
return sizeof(arr) / sizeof(arr[0]);
}
char text[] = "1234567890123456789";
int main (void) {
int i;
int e=getLength(text);
printf("%d\n",e);
for (i = 0; i < e; i++) {
printf("%c\n", text[i]);
}
return 0;
}
because when you pass an array as an argument, it decays to a pointer. So sizeof(arr) yields the size of the pointer (which is 8 bytes on your architecture), not the whole size of the array.
Because sizeof(array) will give you the size of the array pointer and NOT the actual size of the array itself.

Why won't all of my char array get passed (in C)? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C sizeof a passed array
Why sizeof(param_array) is the size of pointer?
I'm new to C, and am a little confused by the type system. I'm trying to write some code to print the number of lower case characters in a string, but only an int-sized piece of my array gets passed to the cntlower function. Why is this?
#include "lecture2.h"
int main(void){
int lowerAns;
char toCount[] = "sdipjsdfzmzp";
printf("toCount size %i\n", sizeof(toCount));
lowerAns = cntlower(toCount);
printf("answer %i\n", lowerAns);
}
int cntlower(char str[]) {
int lowers = 0;
int i = 0;
printf("str size %i\n", sizeof(str));
printf("char size %i\n", sizeof(char));
for(i = 0; i < (sizeof(str)/sizeof(char)); i++) {
if(str[i] >= 'a' && str[i] <= 'z') {
lowers++;
}
}
return lowers;
}
As it is, the output is currently:
toCount size 13
str size 4
char size 1
answer 4
I'm sure the reason for this is obvious for some of you, but unfortunately it isn't for me!
A char str[] argument to a function is actually syntactic sugar for a char*, so sizeof(str) == sizeof(char*). That happens to coincide with sizeof(int) on your platform.

Resources